sqlglot.generator
1from __future__ import annotations 2 3import logging 4import re 5import typing as t 6from collections import defaultdict 7from functools import reduce, wraps 8 9from sqlglot import exp 10from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages 11from sqlglot.helper import apply_index_offset, csv, name_sequence, seq_get 12from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS 13from sqlglot.time import format_time 14from sqlglot.tokens import TokenType 15 16if t.TYPE_CHECKING: 17 from sqlglot._typing import E 18 from sqlglot.dialects.dialect import DialectType 19 20 G = t.TypeVar("G", bound="Generator") 21 GeneratorMethod = t.Callable[[G, E], str] 22 23logger = logging.getLogger("sqlglot") 24 25ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)") 26UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}." 27 28 29def unsupported_args( 30 *args: t.Union[str, t.Tuple[str, str]], 31) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 32 """ 33 Decorator that can be used to mark certain args of an `Expression` subclass as unsupported. 34 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 35 """ 36 diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {} 37 for arg in args: 38 if isinstance(arg, str): 39 diagnostic_by_arg[arg] = None 40 else: 41 diagnostic_by_arg[arg[0]] = arg[1] 42 43 def decorator(func: GeneratorMethod) -> GeneratorMethod: 44 @wraps(func) 45 def _func(generator: G, expression: E) -> str: 46 expression_name = expression.__class__.__name__ 47 dialect_name = generator.dialect.__class__.__name__ 48 49 for arg_name, diagnostic in diagnostic_by_arg.items(): 50 if expression.args.get(arg_name): 51 diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format( 52 arg_name, expression_name, dialect_name 53 ) 54 generator.unsupported(diagnostic) 55 56 return func(generator, expression) 57 58 return _func 59 60 return decorator 61 62 63class _Generator(type): 64 def __new__(cls, clsname, bases, attrs): 65 klass = super().__new__(cls, clsname, bases, attrs) 66 67 # Remove transforms that correspond to unsupported JSONPathPart expressions 68 for part in ALL_JSON_PATH_PARTS - klass.SUPPORTED_JSON_PATH_PARTS: 69 klass.TRANSFORMS.pop(part, None) 70 71 return klass 72 73 74class Generator(metaclass=_Generator): 75 """ 76 Generator converts a given syntax tree to the corresponding SQL string. 77 78 Args: 79 pretty: Whether to format the produced SQL string. 80 Default: False. 81 identify: Determines when an identifier should be quoted. Possible values are: 82 False (default): Never quote, except in cases where it's mandatory by the dialect. 83 True or 'always': Always quote. 84 'safe': Only quote identifiers that are case insensitive. 85 normalize: Whether to normalize identifiers to lowercase. 86 Default: False. 87 pad: The pad size in a formatted string. For example, this affects the indentation of 88 a projection in a query, relative to its nesting level. 89 Default: 2. 90 indent: The indentation size in a formatted string. For example, this affects the 91 indentation of subqueries and filters under a `WHERE` clause. 92 Default: 2. 93 normalize_functions: How to normalize function names. Possible values are: 94 "upper" or True (default): Convert names to uppercase. 95 "lower": Convert names to lowercase. 96 False: Disables function name normalization. 97 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 98 Default ErrorLevel.WARN. 99 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 100 This is only relevant if unsupported_level is ErrorLevel.RAISE. 101 Default: 3 102 leading_comma: Whether the comma is leading or trailing in select expressions. 103 This is only relevant when generating in pretty mode. 104 Default: False 105 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 106 The default is on the smaller end because the length only represents a segment and not the true 107 line length. 108 Default: 80 109 comments: Whether to preserve comments in the output SQL code. 110 Default: True 111 """ 112 113 TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = { 114 **JSON_PATH_PART_TRANSFORMS, 115 exp.AllowedValuesProperty: lambda self, 116 e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}", 117 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 118 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 119 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 120 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 121 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 122 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 123 exp.CaseSpecificColumnConstraint: lambda _, 124 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 125 exp.Ceil: lambda self, e: self.ceil_floor(e), 126 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 127 exp.CharacterSetProperty: lambda self, 128 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 129 exp.ClusteredColumnConstraint: lambda self, 130 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 131 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 132 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 133 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 134 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 135 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 136 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 137 exp.DynamicProperty: lambda *_: "DYNAMIC", 138 exp.EmptyProperty: lambda *_: "EMPTY", 139 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 140 exp.EphemeralColumnConstraint: lambda self, 141 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 142 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 143 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 144 exp.Except: lambda self, e: self.set_operations(e), 145 exp.ExternalProperty: lambda *_: "EXTERNAL", 146 exp.Floor: lambda self, e: self.ceil_floor(e), 147 exp.GlobalProperty: lambda *_: "GLOBAL", 148 exp.HeapProperty: lambda *_: "HEAP", 149 exp.IcebergProperty: lambda *_: "ICEBERG", 150 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 151 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 152 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 153 exp.Intersect: lambda self, e: self.set_operations(e), 154 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 155 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 156 exp.LanguageProperty: lambda self, e: self.naked_property(e), 157 exp.LocationProperty: lambda self, e: self.naked_property(e), 158 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 159 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 160 exp.NonClusteredColumnConstraint: lambda self, 161 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 162 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 163 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 164 exp.OnCommitProperty: lambda _, 165 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 166 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 167 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 168 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 169 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 170 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 171 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 172 exp.ProjectionPolicyColumnConstraint: lambda self, 173 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 174 exp.RemoteWithConnectionModelProperty: lambda self, 175 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 176 exp.ReturnsProperty: lambda self, e: ( 177 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 178 ), 179 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 180 exp.SecureProperty: lambda *_: "SECURE", 181 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 182 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 183 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 184 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 185 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 186 exp.SqlReadWriteProperty: lambda _, e: e.name, 187 exp.SqlSecurityProperty: lambda _, 188 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 189 exp.StabilityProperty: lambda _, e: e.name, 190 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 191 exp.StreamingTableProperty: lambda *_: "STREAMING", 192 exp.StrictProperty: lambda *_: "STRICT", 193 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 194 exp.TemporaryProperty: lambda *_: "TEMPORARY", 195 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 196 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 197 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 198 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 199 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 200 exp.TransientProperty: lambda *_: "TRANSIENT", 201 exp.Union: lambda self, e: self.set_operations(e), 202 exp.UnloggedProperty: lambda *_: "UNLOGGED", 203 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 204 exp.Uuid: lambda *_: "UUID()", 205 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 206 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 207 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 208 exp.VolatileProperty: lambda *_: "VOLATILE", 209 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 210 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 211 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 212 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 213 exp.ForceProperty: lambda *_: "FORCE", 214 } 215 216 # Whether null ordering is supported in order by 217 # True: Full Support, None: No support, False: No support for certain cases 218 # such as window specifications, aggregate functions etc 219 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 220 221 # Whether ignore nulls is inside the agg or outside. 222 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 223 IGNORE_NULLS_IN_FUNC = False 224 225 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 226 LOCKING_READS_SUPPORTED = False 227 228 # Whether the EXCEPT and INTERSECT operations can return duplicates 229 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 230 231 # Wrap derived values in parens, usually standard but spark doesn't support it 232 WRAP_DERIVED_VALUES = True 233 234 # Whether create function uses an AS before the RETURN 235 CREATE_FUNCTION_RETURN_AS = True 236 237 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 238 MATCHED_BY_SOURCE = True 239 240 # Whether the INTERVAL expression works only with values like '1 day' 241 SINGLE_STRING_INTERVAL = False 242 243 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 244 INTERVAL_ALLOWS_PLURAL_FORM = True 245 246 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 247 LIMIT_FETCH = "ALL" 248 249 # Whether limit and fetch allows expresions or just limits 250 LIMIT_ONLY_LITERALS = False 251 252 # Whether a table is allowed to be renamed with a db 253 RENAME_TABLE_WITH_DB = True 254 255 # The separator for grouping sets and rollups 256 GROUPINGS_SEP = "," 257 258 # The string used for creating an index on a table 259 INDEX_ON = "ON" 260 261 # Whether join hints should be generated 262 JOIN_HINTS = True 263 264 # Whether table hints should be generated 265 TABLE_HINTS = True 266 267 # Whether query hints should be generated 268 QUERY_HINTS = True 269 270 # What kind of separator to use for query hints 271 QUERY_HINT_SEP = ", " 272 273 # Whether comparing against booleans (e.g. x IS TRUE) is supported 274 IS_BOOL_ALLOWED = True 275 276 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 277 DUPLICATE_KEY_UPDATE_WITH_SET = True 278 279 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 280 LIMIT_IS_TOP = False 281 282 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 283 RETURNING_END = True 284 285 # Whether to generate an unquoted value for EXTRACT's date part argument 286 EXTRACT_ALLOWS_QUOTES = True 287 288 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 289 TZ_TO_WITH_TIME_ZONE = False 290 291 # Whether the NVL2 function is supported 292 NVL2_SUPPORTED = True 293 294 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 295 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 296 297 # Whether VALUES statements can be used as derived tables. 298 # MySQL 5 and Redshift do not allow this, so when False, it will convert 299 # SELECT * VALUES into SELECT UNION 300 VALUES_AS_TABLE = True 301 302 # Whether the word COLUMN is included when adding a column with ALTER TABLE 303 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 304 305 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 306 UNNEST_WITH_ORDINALITY = True 307 308 # Whether FILTER (WHERE cond) can be used for conditional aggregation 309 AGGREGATE_FILTER_SUPPORTED = True 310 311 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 312 SEMI_ANTI_JOIN_WITH_SIDE = True 313 314 # Whether to include the type of a computed column in the CREATE DDL 315 COMPUTED_COLUMN_WITH_TYPE = True 316 317 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 318 SUPPORTS_TABLE_COPY = True 319 320 # Whether parentheses are required around the table sample's expression 321 TABLESAMPLE_REQUIRES_PARENS = True 322 323 # Whether a table sample clause's size needs to be followed by the ROWS keyword 324 TABLESAMPLE_SIZE_IS_ROWS = True 325 326 # The keyword(s) to use when generating a sample clause 327 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 328 329 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 330 TABLESAMPLE_WITH_METHOD = True 331 332 # The keyword to use when specifying the seed of a sample clause 333 TABLESAMPLE_SEED_KEYWORD = "SEED" 334 335 # Whether COLLATE is a function instead of a binary operator 336 COLLATE_IS_FUNC = False 337 338 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 339 DATA_TYPE_SPECIFIERS_ALLOWED = False 340 341 # Whether conditions require booleans WHERE x = 0 vs WHERE x 342 ENSURE_BOOLS = False 343 344 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 345 CTE_RECURSIVE_KEYWORD_REQUIRED = True 346 347 # Whether CONCAT requires >1 arguments 348 SUPPORTS_SINGLE_ARG_CONCAT = True 349 350 # Whether LAST_DAY function supports a date part argument 351 LAST_DAY_SUPPORTS_DATE_PART = True 352 353 # Whether named columns are allowed in table aliases 354 SUPPORTS_TABLE_ALIAS_COLUMNS = True 355 356 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 357 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 358 359 # What delimiter to use for separating JSON key/value pairs 360 JSON_KEY_VALUE_PAIR_SEP = ":" 361 362 # INSERT OVERWRITE TABLE x override 363 INSERT_OVERWRITE = " OVERWRITE TABLE" 364 365 # Whether the SELECT .. INTO syntax is used instead of CTAS 366 SUPPORTS_SELECT_INTO = False 367 368 # Whether UNLOGGED tables can be created 369 SUPPORTS_UNLOGGED_TABLES = False 370 371 # Whether the CREATE TABLE LIKE statement is supported 372 SUPPORTS_CREATE_TABLE_LIKE = True 373 374 # Whether the LikeProperty needs to be specified inside of the schema clause 375 LIKE_PROPERTY_INSIDE_SCHEMA = False 376 377 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 378 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 379 MULTI_ARG_DISTINCT = True 380 381 # Whether the JSON extraction operators expect a value of type JSON 382 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 383 384 # Whether bracketed keys like ["foo"] are supported in JSON paths 385 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 386 387 # Whether to escape keys using single quotes in JSON paths 388 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 389 390 # The JSONPathPart expressions supported by this dialect 391 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 392 393 # Whether any(f(x) for x in array) can be implemented by this dialect 394 CAN_IMPLEMENT_ARRAY_ANY = False 395 396 # Whether the function TO_NUMBER is supported 397 SUPPORTS_TO_NUMBER = True 398 399 # Whether or not set op modifiers apply to the outer set op or select. 400 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 401 # True means limit 1 happens after the set op, False means it it happens on y. 402 SET_OP_MODIFIERS = True 403 404 # Whether parameters from COPY statement are wrapped in parentheses 405 COPY_PARAMS_ARE_WRAPPED = True 406 407 # Whether values of params are set with "=" token or empty space 408 COPY_PARAMS_EQ_REQUIRED = False 409 410 # Whether COPY statement has INTO keyword 411 COPY_HAS_INTO_KEYWORD = True 412 413 # Whether the conditional TRY(expression) function is supported 414 TRY_SUPPORTED = True 415 416 # Whether the UESCAPE syntax in unicode strings is supported 417 SUPPORTS_UESCAPE = True 418 419 # The keyword to use when generating a star projection with excluded columns 420 STAR_EXCEPT = "EXCEPT" 421 422 # The HEX function name 423 HEX_FUNC = "HEX" 424 425 # The keywords to use when prefixing & separating WITH based properties 426 WITH_PROPERTIES_PREFIX = "WITH" 427 428 # Whether to quote the generated expression of exp.JsonPath 429 QUOTE_JSON_PATH = True 430 431 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 432 PAD_FILL_PATTERN_IS_REQUIRED = False 433 434 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 435 SUPPORTS_EXPLODING_PROJECTIONS = True 436 437 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 438 ARRAY_CONCAT_IS_VAR_LEN = True 439 440 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 441 SUPPORTS_CONVERT_TIMEZONE = False 442 443 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 444 SUPPORTS_MEDIAN = True 445 446 # Whether UNIX_SECONDS(timestamp) is supported 447 SUPPORTS_UNIX_SECONDS = False 448 449 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 450 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 451 452 # The function name of the exp.ArraySize expression 453 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 454 455 # The syntax to use when altering the type of a column 456 ALTER_SET_TYPE = "SET DATA TYPE" 457 458 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 459 # None -> Doesn't support it at all 460 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 461 # True (Postgres) -> Explicitly requires it 462 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 463 464 TYPE_MAPPING = { 465 exp.DataType.Type.DATETIME2: "TIMESTAMP", 466 exp.DataType.Type.NCHAR: "CHAR", 467 exp.DataType.Type.NVARCHAR: "VARCHAR", 468 exp.DataType.Type.MEDIUMTEXT: "TEXT", 469 exp.DataType.Type.LONGTEXT: "TEXT", 470 exp.DataType.Type.TINYTEXT: "TEXT", 471 exp.DataType.Type.BLOB: "VARBINARY", 472 exp.DataType.Type.MEDIUMBLOB: "BLOB", 473 exp.DataType.Type.LONGBLOB: "BLOB", 474 exp.DataType.Type.TINYBLOB: "BLOB", 475 exp.DataType.Type.INET: "INET", 476 exp.DataType.Type.ROWVERSION: "VARBINARY", 477 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 478 } 479 480 TIME_PART_SINGULARS = { 481 "MICROSECONDS": "MICROSECOND", 482 "SECONDS": "SECOND", 483 "MINUTES": "MINUTE", 484 "HOURS": "HOUR", 485 "DAYS": "DAY", 486 "WEEKS": "WEEK", 487 "MONTHS": "MONTH", 488 "QUARTERS": "QUARTER", 489 "YEARS": "YEAR", 490 } 491 492 AFTER_HAVING_MODIFIER_TRANSFORMS = { 493 "cluster": lambda self, e: self.sql(e, "cluster"), 494 "distribute": lambda self, e: self.sql(e, "distribute"), 495 "sort": lambda self, e: self.sql(e, "sort"), 496 "windows": lambda self, e: ( 497 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 498 if e.args.get("windows") 499 else "" 500 ), 501 "qualify": lambda self, e: self.sql(e, "qualify"), 502 } 503 504 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 505 506 STRUCT_DELIMITER = ("<", ">") 507 508 PARAMETER_TOKEN = "@" 509 NAMED_PLACEHOLDER_TOKEN = ":" 510 511 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 512 513 PROPERTIES_LOCATION = { 514 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 515 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 516 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 517 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 518 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 520 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 521 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 522 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 525 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 526 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 527 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 528 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 529 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 530 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 531 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 532 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 533 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 534 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 537 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 538 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 539 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 540 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 541 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 542 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 543 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 544 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 545 exp.HeapProperty: exp.Properties.Location.POST_WITH, 546 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 547 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 548 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 549 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 551 exp.JournalProperty: exp.Properties.Location.POST_NAME, 552 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 553 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 556 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 557 exp.LogProperty: exp.Properties.Location.POST_NAME, 558 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 559 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 560 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 561 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 562 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 563 exp.Order: exp.Properties.Location.POST_SCHEMA, 564 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 565 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 566 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 567 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 568 exp.Property: exp.Properties.Location.POST_WITH, 569 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 570 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 575 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 576 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 577 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 578 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 579 exp.Set: exp.Properties.Location.POST_SCHEMA, 580 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 581 exp.SetProperty: exp.Properties.Location.POST_CREATE, 582 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 583 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 584 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 585 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 586 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 587 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 588 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 589 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 591 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 592 exp.Tags: exp.Properties.Location.POST_WITH, 593 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 594 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 595 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 596 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 597 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 598 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 599 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 600 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 601 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 602 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 603 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 604 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 605 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 606 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 607 } 608 609 # Keywords that can't be used as unquoted identifier names 610 RESERVED_KEYWORDS: t.Set[str] = set() 611 612 # Expressions whose comments are separated from them for better formatting 613 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 614 exp.Command, 615 exp.Create, 616 exp.Describe, 617 exp.Delete, 618 exp.Drop, 619 exp.From, 620 exp.Insert, 621 exp.Join, 622 exp.MultitableInserts, 623 exp.Select, 624 exp.SetOperation, 625 exp.Update, 626 exp.Where, 627 exp.With, 628 ) 629 630 # Expressions that should not have their comments generated in maybe_comment 631 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 632 exp.Binary, 633 exp.SetOperation, 634 ) 635 636 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 637 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 638 exp.Column, 639 exp.Literal, 640 exp.Neg, 641 exp.Paren, 642 ) 643 644 PARAMETERIZABLE_TEXT_TYPES = { 645 exp.DataType.Type.NVARCHAR, 646 exp.DataType.Type.VARCHAR, 647 exp.DataType.Type.CHAR, 648 exp.DataType.Type.NCHAR, 649 } 650 651 # Expressions that need to have all CTEs under them bubbled up to them 652 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 653 654 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 655 656 __slots__ = ( 657 "pretty", 658 "identify", 659 "normalize", 660 "pad", 661 "_indent", 662 "normalize_functions", 663 "unsupported_level", 664 "max_unsupported", 665 "leading_comma", 666 "max_text_width", 667 "comments", 668 "dialect", 669 "unsupported_messages", 670 "_escaped_quote_end", 671 "_escaped_identifier_end", 672 "_next_name", 673 "_identifier_start", 674 "_identifier_end", 675 "_quote_json_path_key_using_brackets", 676 ) 677 678 def __init__( 679 self, 680 pretty: t.Optional[bool] = None, 681 identify: str | bool = False, 682 normalize: bool = False, 683 pad: int = 2, 684 indent: int = 2, 685 normalize_functions: t.Optional[str | bool] = None, 686 unsupported_level: ErrorLevel = ErrorLevel.WARN, 687 max_unsupported: int = 3, 688 leading_comma: bool = False, 689 max_text_width: int = 80, 690 comments: bool = True, 691 dialect: DialectType = None, 692 ): 693 import sqlglot 694 from sqlglot.dialects import Dialect 695 696 self.pretty = pretty if pretty is not None else sqlglot.pretty 697 self.identify = identify 698 self.normalize = normalize 699 self.pad = pad 700 self._indent = indent 701 self.unsupported_level = unsupported_level 702 self.max_unsupported = max_unsupported 703 self.leading_comma = leading_comma 704 self.max_text_width = max_text_width 705 self.comments = comments 706 self.dialect = Dialect.get_or_raise(dialect) 707 708 # This is both a Dialect property and a Generator argument, so we prioritize the latter 709 self.normalize_functions = ( 710 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 711 ) 712 713 self.unsupported_messages: t.List[str] = [] 714 self._escaped_quote_end: str = ( 715 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 716 ) 717 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 718 719 self._next_name = name_sequence("_t") 720 721 self._identifier_start = self.dialect.IDENTIFIER_START 722 self._identifier_end = self.dialect.IDENTIFIER_END 723 724 self._quote_json_path_key_using_brackets = True 725 726 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 727 """ 728 Generates the SQL string corresponding to the given syntax tree. 729 730 Args: 731 expression: The syntax tree. 732 copy: Whether to copy the expression. The generator performs mutations so 733 it is safer to copy. 734 735 Returns: 736 The SQL string corresponding to `expression`. 737 """ 738 if copy: 739 expression = expression.copy() 740 741 expression = self.preprocess(expression) 742 743 self.unsupported_messages = [] 744 sql = self.sql(expression).strip() 745 746 if self.pretty: 747 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 748 749 if self.unsupported_level == ErrorLevel.IGNORE: 750 return sql 751 752 if self.unsupported_level == ErrorLevel.WARN: 753 for msg in self.unsupported_messages: 754 logger.warning(msg) 755 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 756 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 757 758 return sql 759 760 def preprocess(self, expression: exp.Expression) -> exp.Expression: 761 """Apply generic preprocessing transformations to a given expression.""" 762 expression = self._move_ctes_to_top_level(expression) 763 764 if self.ENSURE_BOOLS: 765 from sqlglot.transforms import ensure_bools 766 767 expression = ensure_bools(expression) 768 769 return expression 770 771 def _move_ctes_to_top_level(self, expression: E) -> E: 772 if ( 773 not expression.parent 774 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 775 and any(node.parent is not expression for node in expression.find_all(exp.With)) 776 ): 777 from sqlglot.transforms import move_ctes_to_top_level 778 779 expression = move_ctes_to_top_level(expression) 780 return expression 781 782 def unsupported(self, message: str) -> None: 783 if self.unsupported_level == ErrorLevel.IMMEDIATE: 784 raise UnsupportedError(message) 785 self.unsupported_messages.append(message) 786 787 def sep(self, sep: str = " ") -> str: 788 return f"{sep.strip()}\n" if self.pretty else sep 789 790 def seg(self, sql: str, sep: str = " ") -> str: 791 return f"{self.sep(sep)}{sql}" 792 793 def pad_comment(self, comment: str) -> str: 794 comment = " " + comment if comment[0].strip() else comment 795 comment = comment + " " if comment[-1].strip() else comment 796 return comment 797 798 def maybe_comment( 799 self, 800 sql: str, 801 expression: t.Optional[exp.Expression] = None, 802 comments: t.Optional[t.List[str]] = None, 803 separated: bool = False, 804 ) -> str: 805 comments = ( 806 ((expression and expression.comments) if comments is None else comments) # type: ignore 807 if self.comments 808 else None 809 ) 810 811 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 812 return sql 813 814 comments_sql = " ".join( 815 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 816 ) 817 818 if not comments_sql: 819 return sql 820 821 comments_sql = self._replace_line_breaks(comments_sql) 822 823 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 824 return ( 825 f"{self.sep()}{comments_sql}{sql}" 826 if not sql or sql[0].isspace() 827 else f"{comments_sql}{self.sep()}{sql}" 828 ) 829 830 return f"{sql} {comments_sql}" 831 832 def wrap(self, expression: exp.Expression | str) -> str: 833 this_sql = ( 834 self.sql(expression) 835 if isinstance(expression, exp.UNWRAPPED_QUERIES) 836 else self.sql(expression, "this") 837 ) 838 if not this_sql: 839 return "()" 840 841 this_sql = self.indent(this_sql, level=1, pad=0) 842 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 843 844 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 845 original = self.identify 846 self.identify = False 847 result = func(*args, **kwargs) 848 self.identify = original 849 return result 850 851 def normalize_func(self, name: str) -> str: 852 if self.normalize_functions == "upper" or self.normalize_functions is True: 853 return name.upper() 854 if self.normalize_functions == "lower": 855 return name.lower() 856 return name 857 858 def indent( 859 self, 860 sql: str, 861 level: int = 0, 862 pad: t.Optional[int] = None, 863 skip_first: bool = False, 864 skip_last: bool = False, 865 ) -> str: 866 if not self.pretty or not sql: 867 return sql 868 869 pad = self.pad if pad is None else pad 870 lines = sql.split("\n") 871 872 return "\n".join( 873 ( 874 line 875 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 876 else f"{' ' * (level * self._indent + pad)}{line}" 877 ) 878 for i, line in enumerate(lines) 879 ) 880 881 def sql( 882 self, 883 expression: t.Optional[str | exp.Expression], 884 key: t.Optional[str] = None, 885 comment: bool = True, 886 ) -> str: 887 if not expression: 888 return "" 889 890 if isinstance(expression, str): 891 return expression 892 893 if key: 894 value = expression.args.get(key) 895 if value: 896 return self.sql(value) 897 return "" 898 899 transform = self.TRANSFORMS.get(expression.__class__) 900 901 if callable(transform): 902 sql = transform(self, expression) 903 elif isinstance(expression, exp.Expression): 904 exp_handler_name = f"{expression.key}_sql" 905 906 if hasattr(self, exp_handler_name): 907 sql = getattr(self, exp_handler_name)(expression) 908 elif isinstance(expression, exp.Func): 909 sql = self.function_fallback_sql(expression) 910 elif isinstance(expression, exp.Property): 911 sql = self.property_sql(expression) 912 else: 913 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 914 else: 915 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 916 917 return self.maybe_comment(sql, expression) if self.comments and comment else sql 918 919 def uncache_sql(self, expression: exp.Uncache) -> str: 920 table = self.sql(expression, "this") 921 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 922 return f"UNCACHE TABLE{exists_sql} {table}" 923 924 def cache_sql(self, expression: exp.Cache) -> str: 925 lazy = " LAZY" if expression.args.get("lazy") else "" 926 table = self.sql(expression, "this") 927 options = expression.args.get("options") 928 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 929 sql = self.sql(expression, "expression") 930 sql = f" AS{self.sep()}{sql}" if sql else "" 931 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 932 return self.prepend_ctes(expression, sql) 933 934 def characterset_sql(self, expression: exp.CharacterSet) -> str: 935 if isinstance(expression.parent, exp.Cast): 936 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 937 default = "DEFAULT " if expression.args.get("default") else "" 938 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 939 940 def column_parts(self, expression: exp.Column) -> str: 941 return ".".join( 942 self.sql(part) 943 for part in ( 944 expression.args.get("catalog"), 945 expression.args.get("db"), 946 expression.args.get("table"), 947 expression.args.get("this"), 948 ) 949 if part 950 ) 951 952 def column_sql(self, expression: exp.Column) -> str: 953 join_mark = " (+)" if expression.args.get("join_mark") else "" 954 955 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 956 join_mark = "" 957 self.unsupported("Outer join syntax using the (+) operator is not supported.") 958 959 return f"{self.column_parts(expression)}{join_mark}" 960 961 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 962 this = self.sql(expression, "this") 963 this = f" {this}" if this else "" 964 position = self.sql(expression, "position") 965 return f"{position}{this}" 966 967 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 968 column = self.sql(expression, "this") 969 kind = self.sql(expression, "kind") 970 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 971 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 972 kind = f"{sep}{kind}" if kind else "" 973 constraints = f" {constraints}" if constraints else "" 974 position = self.sql(expression, "position") 975 position = f" {position}" if position else "" 976 977 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 978 kind = "" 979 980 return f"{exists}{column}{kind}{constraints}{position}" 981 982 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 983 this = self.sql(expression, "this") 984 kind_sql = self.sql(expression, "kind").strip() 985 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 986 987 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 988 this = self.sql(expression, "this") 989 if expression.args.get("not_null"): 990 persisted = " PERSISTED NOT NULL" 991 elif expression.args.get("persisted"): 992 persisted = " PERSISTED" 993 else: 994 persisted = "" 995 return f"AS {this}{persisted}" 996 997 def autoincrementcolumnconstraint_sql(self, _) -> str: 998 return self.token_sql(TokenType.AUTO_INCREMENT) 999 1000 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1001 if isinstance(expression.this, list): 1002 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1003 else: 1004 this = self.sql(expression, "this") 1005 1006 return f"COMPRESS {this}" 1007 1008 def generatedasidentitycolumnconstraint_sql( 1009 self, expression: exp.GeneratedAsIdentityColumnConstraint 1010 ) -> str: 1011 this = "" 1012 if expression.this is not None: 1013 on_null = " ON NULL" if expression.args.get("on_null") else "" 1014 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1015 1016 start = expression.args.get("start") 1017 start = f"START WITH {start}" if start else "" 1018 increment = expression.args.get("increment") 1019 increment = f" INCREMENT BY {increment}" if increment else "" 1020 minvalue = expression.args.get("minvalue") 1021 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1022 maxvalue = expression.args.get("maxvalue") 1023 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1024 cycle = expression.args.get("cycle") 1025 cycle_sql = "" 1026 1027 if cycle is not None: 1028 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1029 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1030 1031 sequence_opts = "" 1032 if start or increment or cycle_sql: 1033 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1034 sequence_opts = f" ({sequence_opts.strip()})" 1035 1036 expr = self.sql(expression, "expression") 1037 expr = f"({expr})" if expr else "IDENTITY" 1038 1039 return f"GENERATED{this} AS {expr}{sequence_opts}" 1040 1041 def generatedasrowcolumnconstraint_sql( 1042 self, expression: exp.GeneratedAsRowColumnConstraint 1043 ) -> str: 1044 start = "START" if expression.args.get("start") else "END" 1045 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1046 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1047 1048 def periodforsystemtimeconstraint_sql( 1049 self, expression: exp.PeriodForSystemTimeConstraint 1050 ) -> str: 1051 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1052 1053 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1054 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1055 1056 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1057 return f"AS {self.sql(expression, 'this')}" 1058 1059 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1060 desc = expression.args.get("desc") 1061 if desc is not None: 1062 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1063 return "PRIMARY KEY" 1064 1065 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1066 this = self.sql(expression, "this") 1067 this = f" {this}" if this else "" 1068 index_type = expression.args.get("index_type") 1069 index_type = f" USING {index_type}" if index_type else "" 1070 on_conflict = self.sql(expression, "on_conflict") 1071 on_conflict = f" {on_conflict}" if on_conflict else "" 1072 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1073 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1074 1075 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1076 return self.sql(expression, "this") 1077 1078 def create_sql(self, expression: exp.Create) -> str: 1079 kind = self.sql(expression, "kind") 1080 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1081 properties = expression.args.get("properties") 1082 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1083 1084 this = self.createable_sql(expression, properties_locs) 1085 1086 properties_sql = "" 1087 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1088 exp.Properties.Location.POST_WITH 1089 ): 1090 properties_sql = self.sql( 1091 exp.Properties( 1092 expressions=[ 1093 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1094 *properties_locs[exp.Properties.Location.POST_WITH], 1095 ] 1096 ) 1097 ) 1098 1099 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1100 properties_sql = self.sep() + properties_sql 1101 elif not self.pretty: 1102 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1103 properties_sql = f" {properties_sql}" 1104 1105 begin = " BEGIN" if expression.args.get("begin") else "" 1106 end = " END" if expression.args.get("end") else "" 1107 1108 expression_sql = self.sql(expression, "expression") 1109 if expression_sql: 1110 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1111 1112 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1113 postalias_props_sql = "" 1114 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1115 postalias_props_sql = self.properties( 1116 exp.Properties( 1117 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1118 ), 1119 wrapped=False, 1120 ) 1121 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1122 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1123 1124 postindex_props_sql = "" 1125 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1126 postindex_props_sql = self.properties( 1127 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1128 wrapped=False, 1129 prefix=" ", 1130 ) 1131 1132 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1133 indexes = f" {indexes}" if indexes else "" 1134 index_sql = indexes + postindex_props_sql 1135 1136 replace = " OR REPLACE" if expression.args.get("replace") else "" 1137 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1138 unique = " UNIQUE" if expression.args.get("unique") else "" 1139 1140 clustered = expression.args.get("clustered") 1141 if clustered is None: 1142 clustered_sql = "" 1143 elif clustered: 1144 clustered_sql = " CLUSTERED COLUMNSTORE" 1145 else: 1146 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1147 1148 postcreate_props_sql = "" 1149 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1150 postcreate_props_sql = self.properties( 1151 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1152 sep=" ", 1153 prefix=" ", 1154 wrapped=False, 1155 ) 1156 1157 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1158 1159 postexpression_props_sql = "" 1160 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1161 postexpression_props_sql = self.properties( 1162 exp.Properties( 1163 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1164 ), 1165 sep=" ", 1166 prefix=" ", 1167 wrapped=False, 1168 ) 1169 1170 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1171 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1172 no_schema_binding = ( 1173 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1174 ) 1175 1176 clone = self.sql(expression, "clone") 1177 clone = f" {clone}" if clone else "" 1178 1179 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1180 properties_expression = f"{expression_sql}{properties_sql}" 1181 else: 1182 properties_expression = f"{properties_sql}{expression_sql}" 1183 1184 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1185 return self.prepend_ctes(expression, expression_sql) 1186 1187 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1188 start = self.sql(expression, "start") 1189 start = f"START WITH {start}" if start else "" 1190 increment = self.sql(expression, "increment") 1191 increment = f" INCREMENT BY {increment}" if increment else "" 1192 minvalue = self.sql(expression, "minvalue") 1193 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1194 maxvalue = self.sql(expression, "maxvalue") 1195 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1196 owned = self.sql(expression, "owned") 1197 owned = f" OWNED BY {owned}" if owned else "" 1198 1199 cache = expression.args.get("cache") 1200 if cache is None: 1201 cache_str = "" 1202 elif cache is True: 1203 cache_str = " CACHE" 1204 else: 1205 cache_str = f" CACHE {cache}" 1206 1207 options = self.expressions(expression, key="options", flat=True, sep=" ") 1208 options = f" {options}" if options else "" 1209 1210 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1211 1212 def clone_sql(self, expression: exp.Clone) -> str: 1213 this = self.sql(expression, "this") 1214 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1215 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1216 return f"{shallow}{keyword} {this}" 1217 1218 def describe_sql(self, expression: exp.Describe) -> str: 1219 style = expression.args.get("style") 1220 style = f" {style}" if style else "" 1221 partition = self.sql(expression, "partition") 1222 partition = f" {partition}" if partition else "" 1223 format = self.sql(expression, "format") 1224 format = f" {format}" if format else "" 1225 1226 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1227 1228 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1229 tag = self.sql(expression, "tag") 1230 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1231 1232 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1233 with_ = self.sql(expression, "with") 1234 if with_: 1235 sql = f"{with_}{self.sep()}{sql}" 1236 return sql 1237 1238 def with_sql(self, expression: exp.With) -> str: 1239 sql = self.expressions(expression, flat=True) 1240 recursive = ( 1241 "RECURSIVE " 1242 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1243 else "" 1244 ) 1245 search = self.sql(expression, "search") 1246 search = f" {search}" if search else "" 1247 1248 return f"WITH {recursive}{sql}{search}" 1249 1250 def cte_sql(self, expression: exp.CTE) -> str: 1251 alias = expression.args.get("alias") 1252 if alias: 1253 alias.add_comments(expression.pop_comments()) 1254 1255 alias_sql = self.sql(expression, "alias") 1256 1257 materialized = expression.args.get("materialized") 1258 if materialized is False: 1259 materialized = "NOT MATERIALIZED " 1260 elif materialized: 1261 materialized = "MATERIALIZED " 1262 1263 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1264 1265 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1266 alias = self.sql(expression, "this") 1267 columns = self.expressions(expression, key="columns", flat=True) 1268 columns = f"({columns})" if columns else "" 1269 1270 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1271 columns = "" 1272 self.unsupported("Named columns are not supported in table alias.") 1273 1274 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1275 alias = self._next_name() 1276 1277 return f"{alias}{columns}" 1278 1279 def bitstring_sql(self, expression: exp.BitString) -> str: 1280 this = self.sql(expression, "this") 1281 if self.dialect.BIT_START: 1282 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1283 return f"{int(this, 2)}" 1284 1285 def hexstring_sql( 1286 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1287 ) -> str: 1288 this = self.sql(expression, "this") 1289 is_integer_type = expression.args.get("is_integer") 1290 1291 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1292 not self.dialect.HEX_START and not binary_function_repr 1293 ): 1294 # Integer representation will be returned if: 1295 # - The read dialect treats the hex value as integer literal but not the write 1296 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1297 return f"{int(this, 16)}" 1298 1299 if not is_integer_type: 1300 # Read dialect treats the hex value as BINARY/BLOB 1301 if binary_function_repr: 1302 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1303 return self.func(binary_function_repr, exp.Literal.string(this)) 1304 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1305 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1306 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1307 1308 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1309 1310 def bytestring_sql(self, expression: exp.ByteString) -> str: 1311 this = self.sql(expression, "this") 1312 if self.dialect.BYTE_START: 1313 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1314 return this 1315 1316 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1317 this = self.sql(expression, "this") 1318 escape = expression.args.get("escape") 1319 1320 if self.dialect.UNICODE_START: 1321 escape_substitute = r"\\\1" 1322 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1323 else: 1324 escape_substitute = r"\\u\1" 1325 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1326 1327 if escape: 1328 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1329 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1330 else: 1331 escape_pattern = ESCAPED_UNICODE_RE 1332 escape_sql = "" 1333 1334 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1335 this = escape_pattern.sub(escape_substitute, this) 1336 1337 return f"{left_quote}{this}{right_quote}{escape_sql}" 1338 1339 def rawstring_sql(self, expression: exp.RawString) -> str: 1340 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1341 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1342 1343 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1344 this = self.sql(expression, "this") 1345 specifier = self.sql(expression, "expression") 1346 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1347 return f"{this}{specifier}" 1348 1349 def datatype_sql(self, expression: exp.DataType) -> str: 1350 nested = "" 1351 values = "" 1352 interior = self.expressions(expression, flat=True) 1353 1354 type_value = expression.this 1355 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1356 type_sql = self.sql(expression, "kind") 1357 else: 1358 type_sql = ( 1359 self.TYPE_MAPPING.get(type_value, type_value.value) 1360 if isinstance(type_value, exp.DataType.Type) 1361 else type_value 1362 ) 1363 1364 if interior: 1365 if expression.args.get("nested"): 1366 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1367 if expression.args.get("values") is not None: 1368 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1369 values = self.expressions(expression, key="values", flat=True) 1370 values = f"{delimiters[0]}{values}{delimiters[1]}" 1371 elif type_value == exp.DataType.Type.INTERVAL: 1372 nested = f" {interior}" 1373 else: 1374 nested = f"({interior})" 1375 1376 type_sql = f"{type_sql}{nested}{values}" 1377 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1378 exp.DataType.Type.TIMETZ, 1379 exp.DataType.Type.TIMESTAMPTZ, 1380 ): 1381 type_sql = f"{type_sql} WITH TIME ZONE" 1382 1383 return type_sql 1384 1385 def directory_sql(self, expression: exp.Directory) -> str: 1386 local = "LOCAL " if expression.args.get("local") else "" 1387 row_format = self.sql(expression, "row_format") 1388 row_format = f" {row_format}" if row_format else "" 1389 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1390 1391 def delete_sql(self, expression: exp.Delete) -> str: 1392 this = self.sql(expression, "this") 1393 this = f" FROM {this}" if this else "" 1394 using = self.sql(expression, "using") 1395 using = f" USING {using}" if using else "" 1396 cluster = self.sql(expression, "cluster") 1397 cluster = f" {cluster}" if cluster else "" 1398 where = self.sql(expression, "where") 1399 returning = self.sql(expression, "returning") 1400 limit = self.sql(expression, "limit") 1401 tables = self.expressions(expression, key="tables") 1402 tables = f" {tables}" if tables else "" 1403 if self.RETURNING_END: 1404 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1405 else: 1406 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1407 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1408 1409 def drop_sql(self, expression: exp.Drop) -> str: 1410 this = self.sql(expression, "this") 1411 expressions = self.expressions(expression, flat=True) 1412 expressions = f" ({expressions})" if expressions else "" 1413 kind = expression.args["kind"] 1414 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1415 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1416 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1417 on_cluster = self.sql(expression, "cluster") 1418 on_cluster = f" {on_cluster}" if on_cluster else "" 1419 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1420 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1421 cascade = " CASCADE" if expression.args.get("cascade") else "" 1422 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1423 purge = " PURGE" if expression.args.get("purge") else "" 1424 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1425 1426 def set_operation(self, expression: exp.SetOperation) -> str: 1427 op_type = type(expression) 1428 op_name = op_type.key.upper() 1429 1430 distinct = expression.args.get("distinct") 1431 if ( 1432 distinct is False 1433 and op_type in (exp.Except, exp.Intersect) 1434 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1435 ): 1436 self.unsupported(f"{op_name} ALL is not supported") 1437 1438 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1439 1440 if distinct is None: 1441 distinct = default_distinct 1442 if distinct is None: 1443 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1444 1445 if distinct is default_distinct: 1446 kind = "" 1447 else: 1448 kind = " DISTINCT" if distinct else " ALL" 1449 1450 by_name = " BY NAME" if expression.args.get("by_name") else "" 1451 return f"{op_name}{kind}{by_name}" 1452 1453 def set_operations(self, expression: exp.SetOperation) -> str: 1454 if not self.SET_OP_MODIFIERS: 1455 limit = expression.args.get("limit") 1456 order = expression.args.get("order") 1457 1458 if limit or order: 1459 select = self._move_ctes_to_top_level( 1460 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1461 ) 1462 1463 if limit: 1464 select = select.limit(limit.pop(), copy=False) 1465 if order: 1466 select = select.order_by(order.pop(), copy=False) 1467 return self.sql(select) 1468 1469 sqls: t.List[str] = [] 1470 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1471 1472 while stack: 1473 node = stack.pop() 1474 1475 if isinstance(node, exp.SetOperation): 1476 stack.append(node.expression) 1477 stack.append( 1478 self.maybe_comment( 1479 self.set_operation(node), comments=node.comments, separated=True 1480 ) 1481 ) 1482 stack.append(node.this) 1483 else: 1484 sqls.append(self.sql(node)) 1485 1486 this = self.sep().join(sqls) 1487 this = self.query_modifiers(expression, this) 1488 return self.prepend_ctes(expression, this) 1489 1490 def fetch_sql(self, expression: exp.Fetch) -> str: 1491 direction = expression.args.get("direction") 1492 direction = f" {direction}" if direction else "" 1493 count = self.sql(expression, "count") 1494 count = f" {count}" if count else "" 1495 limit_options = self.sql(expression, "limit_options") 1496 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1497 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1498 1499 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1500 percent = " PERCENT" if expression.args.get("percent") else "" 1501 rows = " ROWS" if expression.args.get("rows") else "" 1502 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1503 if not with_ties and rows: 1504 with_ties = " ONLY" 1505 return f"{percent}{rows}{with_ties}" 1506 1507 def filter_sql(self, expression: exp.Filter) -> str: 1508 if self.AGGREGATE_FILTER_SUPPORTED: 1509 this = self.sql(expression, "this") 1510 where = self.sql(expression, "expression").strip() 1511 return f"{this} FILTER({where})" 1512 1513 agg = expression.this 1514 agg_arg = agg.this 1515 cond = expression.expression.this 1516 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1517 return self.sql(agg) 1518 1519 def hint_sql(self, expression: exp.Hint) -> str: 1520 if not self.QUERY_HINTS: 1521 self.unsupported("Hints are not supported") 1522 return "" 1523 1524 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1525 1526 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1527 using = self.sql(expression, "using") 1528 using = f" USING {using}" if using else "" 1529 columns = self.expressions(expression, key="columns", flat=True) 1530 columns = f"({columns})" if columns else "" 1531 partition_by = self.expressions(expression, key="partition_by", flat=True) 1532 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1533 where = self.sql(expression, "where") 1534 include = self.expressions(expression, key="include", flat=True) 1535 if include: 1536 include = f" INCLUDE ({include})" 1537 with_storage = self.expressions(expression, key="with_storage", flat=True) 1538 with_storage = f" WITH ({with_storage})" if with_storage else "" 1539 tablespace = self.sql(expression, "tablespace") 1540 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1541 on = self.sql(expression, "on") 1542 on = f" ON {on}" if on else "" 1543 1544 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1545 1546 def index_sql(self, expression: exp.Index) -> str: 1547 unique = "UNIQUE " if expression.args.get("unique") else "" 1548 primary = "PRIMARY " if expression.args.get("primary") else "" 1549 amp = "AMP " if expression.args.get("amp") else "" 1550 name = self.sql(expression, "this") 1551 name = f"{name} " if name else "" 1552 table = self.sql(expression, "table") 1553 table = f"{self.INDEX_ON} {table}" if table else "" 1554 1555 index = "INDEX " if not table else "" 1556 1557 params = self.sql(expression, "params") 1558 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1559 1560 def identifier_sql(self, expression: exp.Identifier) -> str: 1561 text = expression.name 1562 lower = text.lower() 1563 text = lower if self.normalize and not expression.quoted else text 1564 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1565 if ( 1566 expression.quoted 1567 or self.dialect.can_identify(text, self.identify) 1568 or lower in self.RESERVED_KEYWORDS 1569 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1570 ): 1571 text = f"{self._identifier_start}{text}{self._identifier_end}" 1572 return text 1573 1574 def hex_sql(self, expression: exp.Hex) -> str: 1575 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1576 if self.dialect.HEX_LOWERCASE: 1577 text = self.func("LOWER", text) 1578 1579 return text 1580 1581 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1582 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1583 if not self.dialect.HEX_LOWERCASE: 1584 text = self.func("LOWER", text) 1585 return text 1586 1587 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1588 input_format = self.sql(expression, "input_format") 1589 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1590 output_format = self.sql(expression, "output_format") 1591 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1592 return self.sep().join((input_format, output_format)) 1593 1594 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1595 string = self.sql(exp.Literal.string(expression.name)) 1596 return f"{prefix}{string}" 1597 1598 def partition_sql(self, expression: exp.Partition) -> str: 1599 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1600 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1601 1602 def properties_sql(self, expression: exp.Properties) -> str: 1603 root_properties = [] 1604 with_properties = [] 1605 1606 for p in expression.expressions: 1607 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1608 if p_loc == exp.Properties.Location.POST_WITH: 1609 with_properties.append(p) 1610 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1611 root_properties.append(p) 1612 1613 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1614 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1615 1616 if root_props and with_props and not self.pretty: 1617 with_props = " " + with_props 1618 1619 return root_props + with_props 1620 1621 def root_properties(self, properties: exp.Properties) -> str: 1622 if properties.expressions: 1623 return self.expressions(properties, indent=False, sep=" ") 1624 return "" 1625 1626 def properties( 1627 self, 1628 properties: exp.Properties, 1629 prefix: str = "", 1630 sep: str = ", ", 1631 suffix: str = "", 1632 wrapped: bool = True, 1633 ) -> str: 1634 if properties.expressions: 1635 expressions = self.expressions(properties, sep=sep, indent=False) 1636 if expressions: 1637 expressions = self.wrap(expressions) if wrapped else expressions 1638 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1639 return "" 1640 1641 def with_properties(self, properties: exp.Properties) -> str: 1642 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1643 1644 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1645 properties_locs = defaultdict(list) 1646 for p in properties.expressions: 1647 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1648 if p_loc != exp.Properties.Location.UNSUPPORTED: 1649 properties_locs[p_loc].append(p) 1650 else: 1651 self.unsupported(f"Unsupported property {p.key}") 1652 1653 return properties_locs 1654 1655 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1656 if isinstance(expression.this, exp.Dot): 1657 return self.sql(expression, "this") 1658 return f"'{expression.name}'" if string_key else expression.name 1659 1660 def property_sql(self, expression: exp.Property) -> str: 1661 property_cls = expression.__class__ 1662 if property_cls == exp.Property: 1663 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1664 1665 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1666 if not property_name: 1667 self.unsupported(f"Unsupported property {expression.key}") 1668 1669 return f"{property_name}={self.sql(expression, 'this')}" 1670 1671 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1672 if self.SUPPORTS_CREATE_TABLE_LIKE: 1673 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1674 options = f" {options}" if options else "" 1675 1676 like = f"LIKE {self.sql(expression, 'this')}{options}" 1677 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1678 like = f"({like})" 1679 1680 return like 1681 1682 if expression.expressions: 1683 self.unsupported("Transpilation of LIKE property options is unsupported") 1684 1685 select = exp.select("*").from_(expression.this).limit(0) 1686 return f"AS {self.sql(select)}" 1687 1688 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1689 no = "NO " if expression.args.get("no") else "" 1690 protection = " PROTECTION" if expression.args.get("protection") else "" 1691 return f"{no}FALLBACK{protection}" 1692 1693 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1694 no = "NO " if expression.args.get("no") else "" 1695 local = expression.args.get("local") 1696 local = f"{local} " if local else "" 1697 dual = "DUAL " if expression.args.get("dual") else "" 1698 before = "BEFORE " if expression.args.get("before") else "" 1699 after = "AFTER " if expression.args.get("after") else "" 1700 return f"{no}{local}{dual}{before}{after}JOURNAL" 1701 1702 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1703 freespace = self.sql(expression, "this") 1704 percent = " PERCENT" if expression.args.get("percent") else "" 1705 return f"FREESPACE={freespace}{percent}" 1706 1707 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1708 if expression.args.get("default"): 1709 property = "DEFAULT" 1710 elif expression.args.get("on"): 1711 property = "ON" 1712 else: 1713 property = "OFF" 1714 return f"CHECKSUM={property}" 1715 1716 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1717 if expression.args.get("no"): 1718 return "NO MERGEBLOCKRATIO" 1719 if expression.args.get("default"): 1720 return "DEFAULT MERGEBLOCKRATIO" 1721 1722 percent = " PERCENT" if expression.args.get("percent") else "" 1723 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1724 1725 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1726 default = expression.args.get("default") 1727 minimum = expression.args.get("minimum") 1728 maximum = expression.args.get("maximum") 1729 if default or minimum or maximum: 1730 if default: 1731 prop = "DEFAULT" 1732 elif minimum: 1733 prop = "MINIMUM" 1734 else: 1735 prop = "MAXIMUM" 1736 return f"{prop} DATABLOCKSIZE" 1737 units = expression.args.get("units") 1738 units = f" {units}" if units else "" 1739 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1740 1741 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1742 autotemp = expression.args.get("autotemp") 1743 always = expression.args.get("always") 1744 default = expression.args.get("default") 1745 manual = expression.args.get("manual") 1746 never = expression.args.get("never") 1747 1748 if autotemp is not None: 1749 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1750 elif always: 1751 prop = "ALWAYS" 1752 elif default: 1753 prop = "DEFAULT" 1754 elif manual: 1755 prop = "MANUAL" 1756 elif never: 1757 prop = "NEVER" 1758 return f"BLOCKCOMPRESSION={prop}" 1759 1760 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1761 no = expression.args.get("no") 1762 no = " NO" if no else "" 1763 concurrent = expression.args.get("concurrent") 1764 concurrent = " CONCURRENT" if concurrent else "" 1765 target = self.sql(expression, "target") 1766 target = f" {target}" if target else "" 1767 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1768 1769 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1770 if isinstance(expression.this, list): 1771 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1772 if expression.this: 1773 modulus = self.sql(expression, "this") 1774 remainder = self.sql(expression, "expression") 1775 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1776 1777 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1778 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1779 return f"FROM ({from_expressions}) TO ({to_expressions})" 1780 1781 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1782 this = self.sql(expression, "this") 1783 1784 for_values_or_default = expression.expression 1785 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1786 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1787 else: 1788 for_values_or_default = " DEFAULT" 1789 1790 return f"PARTITION OF {this}{for_values_or_default}" 1791 1792 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1793 kind = expression.args.get("kind") 1794 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1795 for_or_in = expression.args.get("for_or_in") 1796 for_or_in = f" {for_or_in}" if for_or_in else "" 1797 lock_type = expression.args.get("lock_type") 1798 override = " OVERRIDE" if expression.args.get("override") else "" 1799 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1800 1801 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1802 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1803 statistics = expression.args.get("statistics") 1804 statistics_sql = "" 1805 if statistics is not None: 1806 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1807 return f"{data_sql}{statistics_sql}" 1808 1809 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1810 this = self.sql(expression, "this") 1811 this = f"HISTORY_TABLE={this}" if this else "" 1812 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1813 data_consistency = ( 1814 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1815 ) 1816 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1817 retention_period = ( 1818 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1819 ) 1820 1821 if this: 1822 on_sql = self.func("ON", this, data_consistency, retention_period) 1823 else: 1824 on_sql = "ON" if expression.args.get("on") else "OFF" 1825 1826 sql = f"SYSTEM_VERSIONING={on_sql}" 1827 1828 return f"WITH({sql})" if expression.args.get("with") else sql 1829 1830 def insert_sql(self, expression: exp.Insert) -> str: 1831 hint = self.sql(expression, "hint") 1832 overwrite = expression.args.get("overwrite") 1833 1834 if isinstance(expression.this, exp.Directory): 1835 this = " OVERWRITE" if overwrite else " INTO" 1836 else: 1837 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1838 1839 stored = self.sql(expression, "stored") 1840 stored = f" {stored}" if stored else "" 1841 alternative = expression.args.get("alternative") 1842 alternative = f" OR {alternative}" if alternative else "" 1843 ignore = " IGNORE" if expression.args.get("ignore") else "" 1844 is_function = expression.args.get("is_function") 1845 if is_function: 1846 this = f"{this} FUNCTION" 1847 this = f"{this} {self.sql(expression, 'this')}" 1848 1849 exists = " IF EXISTS" if expression.args.get("exists") else "" 1850 where = self.sql(expression, "where") 1851 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1852 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1853 on_conflict = self.sql(expression, "conflict") 1854 on_conflict = f" {on_conflict}" if on_conflict else "" 1855 by_name = " BY NAME" if expression.args.get("by_name") else "" 1856 returning = self.sql(expression, "returning") 1857 1858 if self.RETURNING_END: 1859 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1860 else: 1861 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1862 1863 partition_by = self.sql(expression, "partition") 1864 partition_by = f" {partition_by}" if partition_by else "" 1865 settings = self.sql(expression, "settings") 1866 settings = f" {settings}" if settings else "" 1867 1868 source = self.sql(expression, "source") 1869 source = f"TABLE {source}" if source else "" 1870 1871 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1872 return self.prepend_ctes(expression, sql) 1873 1874 def introducer_sql(self, expression: exp.Introducer) -> str: 1875 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1876 1877 def kill_sql(self, expression: exp.Kill) -> str: 1878 kind = self.sql(expression, "kind") 1879 kind = f" {kind}" if kind else "" 1880 this = self.sql(expression, "this") 1881 this = f" {this}" if this else "" 1882 return f"KILL{kind}{this}" 1883 1884 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1885 return expression.name 1886 1887 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1888 return expression.name 1889 1890 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1891 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1892 1893 constraint = self.sql(expression, "constraint") 1894 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1895 1896 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1897 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1898 action = self.sql(expression, "action") 1899 1900 expressions = self.expressions(expression, flat=True) 1901 if expressions: 1902 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1903 expressions = f" {set_keyword}{expressions}" 1904 1905 where = self.sql(expression, "where") 1906 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1907 1908 def returning_sql(self, expression: exp.Returning) -> str: 1909 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1910 1911 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1912 fields = self.sql(expression, "fields") 1913 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1914 escaped = self.sql(expression, "escaped") 1915 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1916 items = self.sql(expression, "collection_items") 1917 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1918 keys = self.sql(expression, "map_keys") 1919 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1920 lines = self.sql(expression, "lines") 1921 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1922 null = self.sql(expression, "null") 1923 null = f" NULL DEFINED AS {null}" if null else "" 1924 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1925 1926 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1927 return f"WITH ({self.expressions(expression, flat=True)})" 1928 1929 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1930 this = f"{self.sql(expression, 'this')} INDEX" 1931 target = self.sql(expression, "target") 1932 target = f" FOR {target}" if target else "" 1933 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1934 1935 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1936 this = self.sql(expression, "this") 1937 kind = self.sql(expression, "kind") 1938 expr = self.sql(expression, "expression") 1939 return f"{this} ({kind} => {expr})" 1940 1941 def table_parts(self, expression: exp.Table) -> str: 1942 return ".".join( 1943 self.sql(part) 1944 for part in ( 1945 expression.args.get("catalog"), 1946 expression.args.get("db"), 1947 expression.args.get("this"), 1948 ) 1949 if part is not None 1950 ) 1951 1952 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1953 table = self.table_parts(expression) 1954 only = "ONLY " if expression.args.get("only") else "" 1955 partition = self.sql(expression, "partition") 1956 partition = f" {partition}" if partition else "" 1957 version = self.sql(expression, "version") 1958 version = f" {version}" if version else "" 1959 alias = self.sql(expression, "alias") 1960 alias = f"{sep}{alias}" if alias else "" 1961 1962 sample = self.sql(expression, "sample") 1963 if self.dialect.ALIAS_POST_TABLESAMPLE: 1964 sample_pre_alias = sample 1965 sample_post_alias = "" 1966 else: 1967 sample_pre_alias = "" 1968 sample_post_alias = sample 1969 1970 hints = self.expressions(expression, key="hints", sep=" ") 1971 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1972 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1973 joins = self.indent( 1974 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1975 ) 1976 laterals = self.expressions(expression, key="laterals", sep="") 1977 1978 file_format = self.sql(expression, "format") 1979 if file_format: 1980 pattern = self.sql(expression, "pattern") 1981 pattern = f", PATTERN => {pattern}" if pattern else "" 1982 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1983 1984 ordinality = expression.args.get("ordinality") or "" 1985 if ordinality: 1986 ordinality = f" WITH ORDINALITY{alias}" 1987 alias = "" 1988 1989 when = self.sql(expression, "when") 1990 if when: 1991 table = f"{table} {when}" 1992 1993 changes = self.sql(expression, "changes") 1994 changes = f" {changes}" if changes else "" 1995 1996 rows_from = self.expressions(expression, key="rows_from") 1997 if rows_from: 1998 table = f"ROWS FROM {self.wrap(rows_from)}" 1999 2000 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2001 2002 def tablesample_sql( 2003 self, 2004 expression: exp.TableSample, 2005 tablesample_keyword: t.Optional[str] = None, 2006 ) -> str: 2007 method = self.sql(expression, "method") 2008 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2009 numerator = self.sql(expression, "bucket_numerator") 2010 denominator = self.sql(expression, "bucket_denominator") 2011 field = self.sql(expression, "bucket_field") 2012 field = f" ON {field}" if field else "" 2013 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2014 seed = self.sql(expression, "seed") 2015 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2016 2017 size = self.sql(expression, "size") 2018 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2019 size = f"{size} ROWS" 2020 2021 percent = self.sql(expression, "percent") 2022 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2023 percent = f"{percent} PERCENT" 2024 2025 expr = f"{bucket}{percent}{size}" 2026 if self.TABLESAMPLE_REQUIRES_PARENS: 2027 expr = f"({expr})" 2028 2029 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2030 2031 def pivot_sql(self, expression: exp.Pivot) -> str: 2032 expressions = self.expressions(expression, flat=True) 2033 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2034 2035 if expression.this: 2036 this = self.sql(expression, "this") 2037 if not expressions: 2038 return f"UNPIVOT {this}" 2039 2040 on = f"{self.seg('ON')} {expressions}" 2041 into = self.sql(expression, "into") 2042 into = f"{self.seg('INTO')} {into}" if into else "" 2043 using = self.expressions(expression, key="using", flat=True) 2044 using = f"{self.seg('USING')} {using}" if using else "" 2045 group = self.sql(expression, "group") 2046 return f"{direction} {this}{on}{into}{using}{group}" 2047 2048 alias = self.sql(expression, "alias") 2049 alias = f" AS {alias}" if alias else "" 2050 2051 field = self.sql(expression, "field") 2052 2053 include_nulls = expression.args.get("include_nulls") 2054 if include_nulls is not None: 2055 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2056 else: 2057 nulls = "" 2058 2059 default_on_null = self.sql(expression, "default_on_null") 2060 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2061 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2062 2063 def version_sql(self, expression: exp.Version) -> str: 2064 this = f"FOR {expression.name}" 2065 kind = expression.text("kind") 2066 expr = self.sql(expression, "expression") 2067 return f"{this} {kind} {expr}" 2068 2069 def tuple_sql(self, expression: exp.Tuple) -> str: 2070 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2071 2072 def update_sql(self, expression: exp.Update) -> str: 2073 this = self.sql(expression, "this") 2074 set_sql = self.expressions(expression, flat=True) 2075 from_sql = self.sql(expression, "from") 2076 where_sql = self.sql(expression, "where") 2077 returning = self.sql(expression, "returning") 2078 order = self.sql(expression, "order") 2079 limit = self.sql(expression, "limit") 2080 if self.RETURNING_END: 2081 expression_sql = f"{from_sql}{where_sql}{returning}" 2082 else: 2083 expression_sql = f"{returning}{from_sql}{where_sql}" 2084 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2085 return self.prepend_ctes(expression, sql) 2086 2087 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2088 values_as_table = values_as_table and self.VALUES_AS_TABLE 2089 2090 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2091 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2092 args = self.expressions(expression) 2093 alias = self.sql(expression, "alias") 2094 values = f"VALUES{self.seg('')}{args}" 2095 values = ( 2096 f"({values})" 2097 if self.WRAP_DERIVED_VALUES 2098 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2099 else values 2100 ) 2101 return f"{values} AS {alias}" if alias else values 2102 2103 # Converts `VALUES...` expression into a series of select unions. 2104 alias_node = expression.args.get("alias") 2105 column_names = alias_node and alias_node.columns 2106 2107 selects: t.List[exp.Query] = [] 2108 2109 for i, tup in enumerate(expression.expressions): 2110 row = tup.expressions 2111 2112 if i == 0 and column_names: 2113 row = [ 2114 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2115 ] 2116 2117 selects.append(exp.Select(expressions=row)) 2118 2119 if self.pretty: 2120 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2121 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2122 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2123 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2124 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2125 2126 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2127 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2128 return f"({unions}){alias}" 2129 2130 def var_sql(self, expression: exp.Var) -> str: 2131 return self.sql(expression, "this") 2132 2133 @unsupported_args("expressions") 2134 def into_sql(self, expression: exp.Into) -> str: 2135 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2136 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2137 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2138 2139 def from_sql(self, expression: exp.From) -> str: 2140 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2141 2142 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2143 grouping_sets = self.expressions(expression, indent=False) 2144 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2145 2146 def rollup_sql(self, expression: exp.Rollup) -> str: 2147 expressions = self.expressions(expression, indent=False) 2148 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2149 2150 def cube_sql(self, expression: exp.Cube) -> str: 2151 expressions = self.expressions(expression, indent=False) 2152 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2153 2154 def group_sql(self, expression: exp.Group) -> str: 2155 group_by_all = expression.args.get("all") 2156 if group_by_all is True: 2157 modifier = " ALL" 2158 elif group_by_all is False: 2159 modifier = " DISTINCT" 2160 else: 2161 modifier = "" 2162 2163 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2164 2165 grouping_sets = self.expressions(expression, key="grouping_sets") 2166 cube = self.expressions(expression, key="cube") 2167 rollup = self.expressions(expression, key="rollup") 2168 2169 groupings = csv( 2170 self.seg(grouping_sets) if grouping_sets else "", 2171 self.seg(cube) if cube else "", 2172 self.seg(rollup) if rollup else "", 2173 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2174 sep=self.GROUPINGS_SEP, 2175 ) 2176 2177 if ( 2178 expression.expressions 2179 and groupings 2180 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2181 ): 2182 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2183 2184 return f"{group_by}{groupings}" 2185 2186 def having_sql(self, expression: exp.Having) -> str: 2187 this = self.indent(self.sql(expression, "this")) 2188 return f"{self.seg('HAVING')}{self.sep()}{this}" 2189 2190 def connect_sql(self, expression: exp.Connect) -> str: 2191 start = self.sql(expression, "start") 2192 start = self.seg(f"START WITH {start}") if start else "" 2193 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2194 connect = self.sql(expression, "connect") 2195 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2196 return start + connect 2197 2198 def prior_sql(self, expression: exp.Prior) -> str: 2199 return f"PRIOR {self.sql(expression, 'this')}" 2200 2201 def join_sql(self, expression: exp.Join) -> str: 2202 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2203 side = None 2204 else: 2205 side = expression.side 2206 2207 op_sql = " ".join( 2208 op 2209 for op in ( 2210 expression.method, 2211 "GLOBAL" if expression.args.get("global") else None, 2212 side, 2213 expression.kind, 2214 expression.hint if self.JOIN_HINTS else None, 2215 ) 2216 if op 2217 ) 2218 match_cond = self.sql(expression, "match_condition") 2219 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2220 on_sql = self.sql(expression, "on") 2221 using = expression.args.get("using") 2222 2223 if not on_sql and using: 2224 on_sql = csv(*(self.sql(column) for column in using)) 2225 2226 this = expression.this 2227 this_sql = self.sql(this) 2228 2229 exprs = self.expressions(expression) 2230 if exprs: 2231 this_sql = f"{this_sql},{self.seg(exprs)}" 2232 2233 if on_sql: 2234 on_sql = self.indent(on_sql, skip_first=True) 2235 space = self.seg(" " * self.pad) if self.pretty else " " 2236 if using: 2237 on_sql = f"{space}USING ({on_sql})" 2238 else: 2239 on_sql = f"{space}ON {on_sql}" 2240 elif not op_sql: 2241 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2242 return f" {this_sql}" 2243 2244 return f", {this_sql}" 2245 2246 if op_sql != "STRAIGHT_JOIN": 2247 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2248 2249 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2250 2251 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2252 args = self.expressions(expression, flat=True) 2253 args = f"({args})" if len(args.split(",")) > 1 else args 2254 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2255 2256 def lateral_op(self, expression: exp.Lateral) -> str: 2257 cross_apply = expression.args.get("cross_apply") 2258 2259 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2260 if cross_apply is True: 2261 op = "INNER JOIN " 2262 elif cross_apply is False: 2263 op = "LEFT JOIN " 2264 else: 2265 op = "" 2266 2267 return f"{op}LATERAL" 2268 2269 def lateral_sql(self, expression: exp.Lateral) -> str: 2270 this = self.sql(expression, "this") 2271 2272 if expression.args.get("view"): 2273 alias = expression.args["alias"] 2274 columns = self.expressions(alias, key="columns", flat=True) 2275 table = f" {alias.name}" if alias.name else "" 2276 columns = f" AS {columns}" if columns else "" 2277 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2278 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2279 2280 alias = self.sql(expression, "alias") 2281 alias = f" AS {alias}" if alias else "" 2282 return f"{self.lateral_op(expression)} {this}{alias}" 2283 2284 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2285 this = self.sql(expression, "this") 2286 2287 args = [ 2288 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2289 for e in (expression.args.get(k) for k in ("offset", "expression")) 2290 if e 2291 ] 2292 2293 args_sql = ", ".join(self.sql(e) for e in args) 2294 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2295 expressions = self.expressions(expression, flat=True) 2296 limit_options = self.sql(expression, "limit_options") 2297 expressions = f" BY {expressions}" if expressions else "" 2298 2299 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2300 2301 def offset_sql(self, expression: exp.Offset) -> str: 2302 this = self.sql(expression, "this") 2303 value = expression.expression 2304 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2305 expressions = self.expressions(expression, flat=True) 2306 expressions = f" BY {expressions}" if expressions else "" 2307 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2308 2309 def setitem_sql(self, expression: exp.SetItem) -> str: 2310 kind = self.sql(expression, "kind") 2311 kind = f"{kind} " if kind else "" 2312 this = self.sql(expression, "this") 2313 expressions = self.expressions(expression) 2314 collate = self.sql(expression, "collate") 2315 collate = f" COLLATE {collate}" if collate else "" 2316 global_ = "GLOBAL " if expression.args.get("global") else "" 2317 return f"{global_}{kind}{this}{expressions}{collate}" 2318 2319 def set_sql(self, expression: exp.Set) -> str: 2320 expressions = f" {self.expressions(expression, flat=True)}" 2321 tag = " TAG" if expression.args.get("tag") else "" 2322 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2323 2324 def pragma_sql(self, expression: exp.Pragma) -> str: 2325 return f"PRAGMA {self.sql(expression, 'this')}" 2326 2327 def lock_sql(self, expression: exp.Lock) -> str: 2328 if not self.LOCKING_READS_SUPPORTED: 2329 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2330 return "" 2331 2332 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2333 expressions = self.expressions(expression, flat=True) 2334 expressions = f" OF {expressions}" if expressions else "" 2335 wait = expression.args.get("wait") 2336 2337 if wait is not None: 2338 if isinstance(wait, exp.Literal): 2339 wait = f" WAIT {self.sql(wait)}" 2340 else: 2341 wait = " NOWAIT" if wait else " SKIP LOCKED" 2342 2343 return f"{lock_type}{expressions}{wait or ''}" 2344 2345 def literal_sql(self, expression: exp.Literal) -> str: 2346 text = expression.this or "" 2347 if expression.is_string: 2348 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2349 return text 2350 2351 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2352 if self.dialect.ESCAPED_SEQUENCES: 2353 to_escaped = self.dialect.ESCAPED_SEQUENCES 2354 text = "".join( 2355 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2356 ) 2357 2358 return self._replace_line_breaks(text).replace( 2359 self.dialect.QUOTE_END, self._escaped_quote_end 2360 ) 2361 2362 def loaddata_sql(self, expression: exp.LoadData) -> str: 2363 local = " LOCAL" if expression.args.get("local") else "" 2364 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2365 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2366 this = f" INTO TABLE {self.sql(expression, 'this')}" 2367 partition = self.sql(expression, "partition") 2368 partition = f" {partition}" if partition else "" 2369 input_format = self.sql(expression, "input_format") 2370 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2371 serde = self.sql(expression, "serde") 2372 serde = f" SERDE {serde}" if serde else "" 2373 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2374 2375 def null_sql(self, *_) -> str: 2376 return "NULL" 2377 2378 def boolean_sql(self, expression: exp.Boolean) -> str: 2379 return "TRUE" if expression.this else "FALSE" 2380 2381 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2382 this = self.sql(expression, "this") 2383 this = f"{this} " if this else this 2384 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2385 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2386 2387 def withfill_sql(self, expression: exp.WithFill) -> str: 2388 from_sql = self.sql(expression, "from") 2389 from_sql = f" FROM {from_sql}" if from_sql else "" 2390 to_sql = self.sql(expression, "to") 2391 to_sql = f" TO {to_sql}" if to_sql else "" 2392 step_sql = self.sql(expression, "step") 2393 step_sql = f" STEP {step_sql}" if step_sql else "" 2394 interpolated_values = [ 2395 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2396 if isinstance(e, exp.Alias) 2397 else self.sql(e, "this") 2398 for e in expression.args.get("interpolate") or [] 2399 ] 2400 interpolate = ( 2401 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2402 ) 2403 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2404 2405 def cluster_sql(self, expression: exp.Cluster) -> str: 2406 return self.op_expressions("CLUSTER BY", expression) 2407 2408 def distribute_sql(self, expression: exp.Distribute) -> str: 2409 return self.op_expressions("DISTRIBUTE BY", expression) 2410 2411 def sort_sql(self, expression: exp.Sort) -> str: 2412 return self.op_expressions("SORT BY", expression) 2413 2414 def ordered_sql(self, expression: exp.Ordered) -> str: 2415 desc = expression.args.get("desc") 2416 asc = not desc 2417 2418 nulls_first = expression.args.get("nulls_first") 2419 nulls_last = not nulls_first 2420 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2421 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2422 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2423 2424 this = self.sql(expression, "this") 2425 2426 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2427 nulls_sort_change = "" 2428 if nulls_first and ( 2429 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2430 ): 2431 nulls_sort_change = " NULLS FIRST" 2432 elif ( 2433 nulls_last 2434 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2435 and not nulls_are_last 2436 ): 2437 nulls_sort_change = " NULLS LAST" 2438 2439 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2440 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2441 window = expression.find_ancestor(exp.Window, exp.Select) 2442 if isinstance(window, exp.Window) and window.args.get("spec"): 2443 self.unsupported( 2444 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2445 ) 2446 nulls_sort_change = "" 2447 elif self.NULL_ORDERING_SUPPORTED is False and ( 2448 (asc and nulls_sort_change == " NULLS LAST") 2449 or (desc and nulls_sort_change == " NULLS FIRST") 2450 ): 2451 # BigQuery does not allow these ordering/nulls combinations when used under 2452 # an aggregation func or under a window containing one 2453 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2454 2455 if isinstance(ancestor, exp.Window): 2456 ancestor = ancestor.this 2457 if isinstance(ancestor, exp.AggFunc): 2458 self.unsupported( 2459 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2460 ) 2461 nulls_sort_change = "" 2462 elif self.NULL_ORDERING_SUPPORTED is None: 2463 if expression.this.is_int: 2464 self.unsupported( 2465 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2466 ) 2467 elif not isinstance(expression.this, exp.Rand): 2468 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2469 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2470 nulls_sort_change = "" 2471 2472 with_fill = self.sql(expression, "with_fill") 2473 with_fill = f" {with_fill}" if with_fill else "" 2474 2475 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2476 2477 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2478 window_frame = self.sql(expression, "window_frame") 2479 window_frame = f"{window_frame} " if window_frame else "" 2480 2481 this = self.sql(expression, "this") 2482 2483 return f"{window_frame}{this}" 2484 2485 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2486 partition = self.partition_by_sql(expression) 2487 order = self.sql(expression, "order") 2488 measures = self.expressions(expression, key="measures") 2489 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2490 rows = self.sql(expression, "rows") 2491 rows = self.seg(rows) if rows else "" 2492 after = self.sql(expression, "after") 2493 after = self.seg(after) if after else "" 2494 pattern = self.sql(expression, "pattern") 2495 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2496 definition_sqls = [ 2497 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2498 for definition in expression.args.get("define", []) 2499 ] 2500 definitions = self.expressions(sqls=definition_sqls) 2501 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2502 body = "".join( 2503 ( 2504 partition, 2505 order, 2506 measures, 2507 rows, 2508 after, 2509 pattern, 2510 define, 2511 ) 2512 ) 2513 alias = self.sql(expression, "alias") 2514 alias = f" {alias}" if alias else "" 2515 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2516 2517 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2518 limit = expression.args.get("limit") 2519 2520 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2521 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2522 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2523 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2524 2525 return csv( 2526 *sqls, 2527 *[self.sql(join) for join in expression.args.get("joins") or []], 2528 self.sql(expression, "match"), 2529 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2530 self.sql(expression, "prewhere"), 2531 self.sql(expression, "where"), 2532 self.sql(expression, "connect"), 2533 self.sql(expression, "group"), 2534 self.sql(expression, "having"), 2535 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2536 self.sql(expression, "order"), 2537 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2538 *self.after_limit_modifiers(expression), 2539 self.options_modifier(expression), 2540 sep="", 2541 ) 2542 2543 def options_modifier(self, expression: exp.Expression) -> str: 2544 options = self.expressions(expression, key="options") 2545 return f" {options}" if options else "" 2546 2547 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2548 return "" 2549 2550 def offset_limit_modifiers( 2551 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2552 ) -> t.List[str]: 2553 return [ 2554 self.sql(expression, "offset") if fetch else self.sql(limit), 2555 self.sql(limit) if fetch else self.sql(expression, "offset"), 2556 ] 2557 2558 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2559 locks = self.expressions(expression, key="locks", sep=" ") 2560 locks = f" {locks}" if locks else "" 2561 return [locks, self.sql(expression, "sample")] 2562 2563 def select_sql(self, expression: exp.Select) -> str: 2564 into = expression.args.get("into") 2565 if not self.SUPPORTS_SELECT_INTO and into: 2566 into.pop() 2567 2568 hint = self.sql(expression, "hint") 2569 distinct = self.sql(expression, "distinct") 2570 distinct = f" {distinct}" if distinct else "" 2571 kind = self.sql(expression, "kind") 2572 2573 limit = expression.args.get("limit") 2574 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2575 top = self.limit_sql(limit, top=True) 2576 limit.pop() 2577 else: 2578 top = "" 2579 2580 expressions = self.expressions(expression) 2581 2582 if kind: 2583 if kind in self.SELECT_KINDS: 2584 kind = f" AS {kind}" 2585 else: 2586 if kind == "STRUCT": 2587 expressions = self.expressions( 2588 sqls=[ 2589 self.sql( 2590 exp.Struct( 2591 expressions=[ 2592 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2593 if isinstance(e, exp.Alias) 2594 else e 2595 for e in expression.expressions 2596 ] 2597 ) 2598 ) 2599 ] 2600 ) 2601 kind = "" 2602 2603 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2604 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2605 2606 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2607 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2608 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2609 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2610 sql = self.query_modifiers( 2611 expression, 2612 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2613 self.sql(expression, "into", comment=False), 2614 self.sql(expression, "from", comment=False), 2615 ) 2616 2617 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2618 if expression.args.get("with"): 2619 sql = self.maybe_comment(sql, expression) 2620 expression.pop_comments() 2621 2622 sql = self.prepend_ctes(expression, sql) 2623 2624 if not self.SUPPORTS_SELECT_INTO and into: 2625 if into.args.get("temporary"): 2626 table_kind = " TEMPORARY" 2627 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2628 table_kind = " UNLOGGED" 2629 else: 2630 table_kind = "" 2631 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2632 2633 return sql 2634 2635 def schema_sql(self, expression: exp.Schema) -> str: 2636 this = self.sql(expression, "this") 2637 sql = self.schema_columns_sql(expression) 2638 return f"{this} {sql}" if this and sql else this or sql 2639 2640 def schema_columns_sql(self, expression: exp.Schema) -> str: 2641 if expression.expressions: 2642 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2643 return "" 2644 2645 def star_sql(self, expression: exp.Star) -> str: 2646 except_ = self.expressions(expression, key="except", flat=True) 2647 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2648 replace = self.expressions(expression, key="replace", flat=True) 2649 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2650 rename = self.expressions(expression, key="rename", flat=True) 2651 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2652 return f"*{except_}{replace}{rename}" 2653 2654 def parameter_sql(self, expression: exp.Parameter) -> str: 2655 this = self.sql(expression, "this") 2656 return f"{self.PARAMETER_TOKEN}{this}" 2657 2658 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2659 this = self.sql(expression, "this") 2660 kind = expression.text("kind") 2661 if kind: 2662 kind = f"{kind}." 2663 return f"@@{kind}{this}" 2664 2665 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2666 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2667 2668 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2669 alias = self.sql(expression, "alias") 2670 alias = f"{sep}{alias}" if alias else "" 2671 sample = self.sql(expression, "sample") 2672 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2673 alias = f"{sample}{alias}" 2674 2675 # Set to None so it's not generated again by self.query_modifiers() 2676 expression.set("sample", None) 2677 2678 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2679 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2680 return self.prepend_ctes(expression, sql) 2681 2682 def qualify_sql(self, expression: exp.Qualify) -> str: 2683 this = self.indent(self.sql(expression, "this")) 2684 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2685 2686 def unnest_sql(self, expression: exp.Unnest) -> str: 2687 args = self.expressions(expression, flat=True) 2688 2689 alias = expression.args.get("alias") 2690 offset = expression.args.get("offset") 2691 2692 if self.UNNEST_WITH_ORDINALITY: 2693 if alias and isinstance(offset, exp.Expression): 2694 alias.append("columns", offset) 2695 2696 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2697 columns = alias.columns 2698 alias = self.sql(columns[0]) if columns else "" 2699 else: 2700 alias = self.sql(alias) 2701 2702 alias = f" AS {alias}" if alias else alias 2703 if self.UNNEST_WITH_ORDINALITY: 2704 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2705 else: 2706 if isinstance(offset, exp.Expression): 2707 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2708 elif offset: 2709 suffix = f"{alias} WITH OFFSET" 2710 else: 2711 suffix = alias 2712 2713 return f"UNNEST({args}){suffix}" 2714 2715 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2716 return "" 2717 2718 def where_sql(self, expression: exp.Where) -> str: 2719 this = self.indent(self.sql(expression, "this")) 2720 return f"{self.seg('WHERE')}{self.sep()}{this}" 2721 2722 def window_sql(self, expression: exp.Window) -> str: 2723 this = self.sql(expression, "this") 2724 partition = self.partition_by_sql(expression) 2725 order = expression.args.get("order") 2726 order = self.order_sql(order, flat=True) if order else "" 2727 spec = self.sql(expression, "spec") 2728 alias = self.sql(expression, "alias") 2729 over = self.sql(expression, "over") or "OVER" 2730 2731 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2732 2733 first = expression.args.get("first") 2734 if first is None: 2735 first = "" 2736 else: 2737 first = "FIRST" if first else "LAST" 2738 2739 if not partition and not order and not spec and alias: 2740 return f"{this} {alias}" 2741 2742 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2743 return f"{this} ({args})" 2744 2745 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2746 partition = self.expressions(expression, key="partition_by", flat=True) 2747 return f"PARTITION BY {partition}" if partition else "" 2748 2749 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2750 kind = self.sql(expression, "kind") 2751 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2752 end = ( 2753 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2754 or "CURRENT ROW" 2755 ) 2756 return f"{kind} BETWEEN {start} AND {end}" 2757 2758 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2759 this = self.sql(expression, "this") 2760 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2761 return f"{this} WITHIN GROUP ({expression_sql})" 2762 2763 def between_sql(self, expression: exp.Between) -> str: 2764 this = self.sql(expression, "this") 2765 low = self.sql(expression, "low") 2766 high = self.sql(expression, "high") 2767 return f"{this} BETWEEN {low} AND {high}" 2768 2769 def bracket_offset_expressions( 2770 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2771 ) -> t.List[exp.Expression]: 2772 return apply_index_offset( 2773 expression.this, 2774 expression.expressions, 2775 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2776 ) 2777 2778 def bracket_sql(self, expression: exp.Bracket) -> str: 2779 expressions = self.bracket_offset_expressions(expression) 2780 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2781 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2782 2783 def all_sql(self, expression: exp.All) -> str: 2784 return f"ALL {self.wrap(expression)}" 2785 2786 def any_sql(self, expression: exp.Any) -> str: 2787 this = self.sql(expression, "this") 2788 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2789 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2790 this = self.wrap(this) 2791 return f"ANY{this}" 2792 return f"ANY {this}" 2793 2794 def exists_sql(self, expression: exp.Exists) -> str: 2795 return f"EXISTS{self.wrap(expression)}" 2796 2797 def case_sql(self, expression: exp.Case) -> str: 2798 this = self.sql(expression, "this") 2799 statements = [f"CASE {this}" if this else "CASE"] 2800 2801 for e in expression.args["ifs"]: 2802 statements.append(f"WHEN {self.sql(e, 'this')}") 2803 statements.append(f"THEN {self.sql(e, 'true')}") 2804 2805 default = self.sql(expression, "default") 2806 2807 if default: 2808 statements.append(f"ELSE {default}") 2809 2810 statements.append("END") 2811 2812 if self.pretty and self.too_wide(statements): 2813 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2814 2815 return " ".join(statements) 2816 2817 def constraint_sql(self, expression: exp.Constraint) -> str: 2818 this = self.sql(expression, "this") 2819 expressions = self.expressions(expression, flat=True) 2820 return f"CONSTRAINT {this} {expressions}" 2821 2822 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2823 order = expression.args.get("order") 2824 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2825 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2826 2827 def extract_sql(self, expression: exp.Extract) -> str: 2828 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2829 expression_sql = self.sql(expression, "expression") 2830 return f"EXTRACT({this} FROM {expression_sql})" 2831 2832 def trim_sql(self, expression: exp.Trim) -> str: 2833 trim_type = self.sql(expression, "position") 2834 2835 if trim_type == "LEADING": 2836 func_name = "LTRIM" 2837 elif trim_type == "TRAILING": 2838 func_name = "RTRIM" 2839 else: 2840 func_name = "TRIM" 2841 2842 return self.func(func_name, expression.this, expression.expression) 2843 2844 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2845 args = expression.expressions 2846 if isinstance(expression, exp.ConcatWs): 2847 args = args[1:] # Skip the delimiter 2848 2849 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2850 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2851 2852 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2853 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2854 2855 return args 2856 2857 def concat_sql(self, expression: exp.Concat) -> str: 2858 expressions = self.convert_concat_args(expression) 2859 2860 # Some dialects don't allow a single-argument CONCAT call 2861 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2862 return self.sql(expressions[0]) 2863 2864 return self.func("CONCAT", *expressions) 2865 2866 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2867 return self.func( 2868 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2869 ) 2870 2871 def check_sql(self, expression: exp.Check) -> str: 2872 this = self.sql(expression, key="this") 2873 return f"CHECK ({this})" 2874 2875 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2876 expressions = self.expressions(expression, flat=True) 2877 expressions = f" ({expressions})" if expressions else "" 2878 reference = self.sql(expression, "reference") 2879 reference = f" {reference}" if reference else "" 2880 delete = self.sql(expression, "delete") 2881 delete = f" ON DELETE {delete}" if delete else "" 2882 update = self.sql(expression, "update") 2883 update = f" ON UPDATE {update}" if update else "" 2884 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2885 2886 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2887 expressions = self.expressions(expression, flat=True) 2888 options = self.expressions(expression, key="options", flat=True, sep=" ") 2889 options = f" {options}" if options else "" 2890 return f"PRIMARY KEY ({expressions}){options}" 2891 2892 def if_sql(self, expression: exp.If) -> str: 2893 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2894 2895 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2896 modifier = expression.args.get("modifier") 2897 modifier = f" {modifier}" if modifier else "" 2898 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2899 2900 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2901 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2902 2903 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2904 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2905 2906 if expression.args.get("escape"): 2907 path = self.escape_str(path) 2908 2909 if self.QUOTE_JSON_PATH: 2910 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2911 2912 return path 2913 2914 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2915 if isinstance(expression, exp.JSONPathPart): 2916 transform = self.TRANSFORMS.get(expression.__class__) 2917 if not callable(transform): 2918 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2919 return "" 2920 2921 return transform(self, expression) 2922 2923 if isinstance(expression, int): 2924 return str(expression) 2925 2926 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2927 escaped = expression.replace("'", "\\'") 2928 escaped = f"\\'{expression}\\'" 2929 else: 2930 escaped = expression.replace('"', '\\"') 2931 escaped = f'"{escaped}"' 2932 2933 return escaped 2934 2935 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2936 return f"{self.sql(expression, 'this')} FORMAT JSON" 2937 2938 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2939 null_handling = expression.args.get("null_handling") 2940 null_handling = f" {null_handling}" if null_handling else "" 2941 2942 unique_keys = expression.args.get("unique_keys") 2943 if unique_keys is not None: 2944 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2945 else: 2946 unique_keys = "" 2947 2948 return_type = self.sql(expression, "return_type") 2949 return_type = f" RETURNING {return_type}" if return_type else "" 2950 encoding = self.sql(expression, "encoding") 2951 encoding = f" ENCODING {encoding}" if encoding else "" 2952 2953 return self.func( 2954 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2955 *expression.expressions, 2956 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2957 ) 2958 2959 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2960 return self.jsonobject_sql(expression) 2961 2962 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2963 null_handling = expression.args.get("null_handling") 2964 null_handling = f" {null_handling}" if null_handling else "" 2965 return_type = self.sql(expression, "return_type") 2966 return_type = f" RETURNING {return_type}" if return_type else "" 2967 strict = " STRICT" if expression.args.get("strict") else "" 2968 return self.func( 2969 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2970 ) 2971 2972 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2973 this = self.sql(expression, "this") 2974 order = self.sql(expression, "order") 2975 null_handling = expression.args.get("null_handling") 2976 null_handling = f" {null_handling}" if null_handling else "" 2977 return_type = self.sql(expression, "return_type") 2978 return_type = f" RETURNING {return_type}" if return_type else "" 2979 strict = " STRICT" if expression.args.get("strict") else "" 2980 return self.func( 2981 "JSON_ARRAYAGG", 2982 this, 2983 suffix=f"{order}{null_handling}{return_type}{strict})", 2984 ) 2985 2986 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2987 path = self.sql(expression, "path") 2988 path = f" PATH {path}" if path else "" 2989 nested_schema = self.sql(expression, "nested_schema") 2990 2991 if nested_schema: 2992 return f"NESTED{path} {nested_schema}" 2993 2994 this = self.sql(expression, "this") 2995 kind = self.sql(expression, "kind") 2996 kind = f" {kind}" if kind else "" 2997 return f"{this}{kind}{path}" 2998 2999 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3000 return self.func("COLUMNS", *expression.expressions) 3001 3002 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3003 this = self.sql(expression, "this") 3004 path = self.sql(expression, "path") 3005 path = f", {path}" if path else "" 3006 error_handling = expression.args.get("error_handling") 3007 error_handling = f" {error_handling}" if error_handling else "" 3008 empty_handling = expression.args.get("empty_handling") 3009 empty_handling = f" {empty_handling}" if empty_handling else "" 3010 schema = self.sql(expression, "schema") 3011 return self.func( 3012 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3013 ) 3014 3015 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3016 this = self.sql(expression, "this") 3017 kind = self.sql(expression, "kind") 3018 path = self.sql(expression, "path") 3019 path = f" {path}" if path else "" 3020 as_json = " AS JSON" if expression.args.get("as_json") else "" 3021 return f"{this} {kind}{path}{as_json}" 3022 3023 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3024 this = self.sql(expression, "this") 3025 path = self.sql(expression, "path") 3026 path = f", {path}" if path else "" 3027 expressions = self.expressions(expression) 3028 with_ = ( 3029 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3030 if expressions 3031 else "" 3032 ) 3033 return f"OPENJSON({this}{path}){with_}" 3034 3035 def in_sql(self, expression: exp.In) -> str: 3036 query = expression.args.get("query") 3037 unnest = expression.args.get("unnest") 3038 field = expression.args.get("field") 3039 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3040 3041 if query: 3042 in_sql = self.sql(query) 3043 elif unnest: 3044 in_sql = self.in_unnest_op(unnest) 3045 elif field: 3046 in_sql = self.sql(field) 3047 else: 3048 in_sql = f"({self.expressions(expression, flat=True)})" 3049 3050 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3051 3052 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3053 return f"(SELECT {self.sql(unnest)})" 3054 3055 def interval_sql(self, expression: exp.Interval) -> str: 3056 unit = self.sql(expression, "unit") 3057 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3058 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3059 unit = f" {unit}" if unit else "" 3060 3061 if self.SINGLE_STRING_INTERVAL: 3062 this = expression.this.name if expression.this else "" 3063 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3064 3065 this = self.sql(expression, "this") 3066 if this: 3067 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3068 this = f" {this}" if unwrapped else f" ({this})" 3069 3070 return f"INTERVAL{this}{unit}" 3071 3072 def return_sql(self, expression: exp.Return) -> str: 3073 return f"RETURN {self.sql(expression, 'this')}" 3074 3075 def reference_sql(self, expression: exp.Reference) -> str: 3076 this = self.sql(expression, "this") 3077 expressions = self.expressions(expression, flat=True) 3078 expressions = f"({expressions})" if expressions else "" 3079 options = self.expressions(expression, key="options", flat=True, sep=" ") 3080 options = f" {options}" if options else "" 3081 return f"REFERENCES {this}{expressions}{options}" 3082 3083 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3084 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3085 parent = expression.parent 3086 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3087 return self.func( 3088 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3089 ) 3090 3091 def paren_sql(self, expression: exp.Paren) -> str: 3092 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3093 return f"({sql}{self.seg(')', sep='')}" 3094 3095 def neg_sql(self, expression: exp.Neg) -> str: 3096 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3097 this_sql = self.sql(expression, "this") 3098 sep = " " if this_sql[0] == "-" else "" 3099 return f"-{sep}{this_sql}" 3100 3101 def not_sql(self, expression: exp.Not) -> str: 3102 return f"NOT {self.sql(expression, 'this')}" 3103 3104 def alias_sql(self, expression: exp.Alias) -> str: 3105 alias = self.sql(expression, "alias") 3106 alias = f" AS {alias}" if alias else "" 3107 return f"{self.sql(expression, 'this')}{alias}" 3108 3109 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3110 alias = expression.args["alias"] 3111 3112 identifier_alias = isinstance(alias, exp.Identifier) 3113 literal_alias = isinstance(alias, exp.Literal) 3114 3115 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3116 alias.replace(exp.Literal.string(alias.output_name)) 3117 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3118 alias.replace(exp.to_identifier(alias.output_name)) 3119 3120 return self.alias_sql(expression) 3121 3122 def aliases_sql(self, expression: exp.Aliases) -> str: 3123 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3124 3125 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3126 this = self.sql(expression, "this") 3127 index = self.sql(expression, "expression") 3128 return f"{this} AT {index}" 3129 3130 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3131 this = self.sql(expression, "this") 3132 zone = self.sql(expression, "zone") 3133 return f"{this} AT TIME ZONE {zone}" 3134 3135 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3136 this = self.sql(expression, "this") 3137 zone = self.sql(expression, "zone") 3138 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3139 3140 def add_sql(self, expression: exp.Add) -> str: 3141 return self.binary(expression, "+") 3142 3143 def and_sql( 3144 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3145 ) -> str: 3146 return self.connector_sql(expression, "AND", stack) 3147 3148 def or_sql( 3149 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3150 ) -> str: 3151 return self.connector_sql(expression, "OR", stack) 3152 3153 def xor_sql( 3154 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3155 ) -> str: 3156 return self.connector_sql(expression, "XOR", stack) 3157 3158 def connector_sql( 3159 self, 3160 expression: exp.Connector, 3161 op: str, 3162 stack: t.Optional[t.List[str | exp.Expression]] = None, 3163 ) -> str: 3164 if stack is not None: 3165 if expression.expressions: 3166 stack.append(self.expressions(expression, sep=f" {op} ")) 3167 else: 3168 stack.append(expression.right) 3169 if expression.comments and self.comments: 3170 for comment in expression.comments: 3171 if comment: 3172 op += f" /*{self.pad_comment(comment)}*/" 3173 stack.extend((op, expression.left)) 3174 return op 3175 3176 stack = [expression] 3177 sqls: t.List[str] = [] 3178 ops = set() 3179 3180 while stack: 3181 node = stack.pop() 3182 if isinstance(node, exp.Connector): 3183 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3184 else: 3185 sql = self.sql(node) 3186 if sqls and sqls[-1] in ops: 3187 sqls[-1] += f" {sql}" 3188 else: 3189 sqls.append(sql) 3190 3191 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3192 return sep.join(sqls) 3193 3194 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3195 return self.binary(expression, "&") 3196 3197 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3198 return self.binary(expression, "<<") 3199 3200 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3201 return f"~{self.sql(expression, 'this')}" 3202 3203 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3204 return self.binary(expression, "|") 3205 3206 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3207 return self.binary(expression, ">>") 3208 3209 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3210 return self.binary(expression, "^") 3211 3212 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3213 format_sql = self.sql(expression, "format") 3214 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3215 to_sql = self.sql(expression, "to") 3216 to_sql = f" {to_sql}" if to_sql else "" 3217 action = self.sql(expression, "action") 3218 action = f" {action}" if action else "" 3219 default = self.sql(expression, "default") 3220 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3221 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3222 3223 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3224 zone = self.sql(expression, "this") 3225 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3226 3227 def collate_sql(self, expression: exp.Collate) -> str: 3228 if self.COLLATE_IS_FUNC: 3229 return self.function_fallback_sql(expression) 3230 return self.binary(expression, "COLLATE") 3231 3232 def command_sql(self, expression: exp.Command) -> str: 3233 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3234 3235 def comment_sql(self, expression: exp.Comment) -> str: 3236 this = self.sql(expression, "this") 3237 kind = expression.args["kind"] 3238 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3239 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3240 expression_sql = self.sql(expression, "expression") 3241 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3242 3243 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3244 this = self.sql(expression, "this") 3245 delete = " DELETE" if expression.args.get("delete") else "" 3246 recompress = self.sql(expression, "recompress") 3247 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3248 to_disk = self.sql(expression, "to_disk") 3249 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3250 to_volume = self.sql(expression, "to_volume") 3251 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3252 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3253 3254 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3255 where = self.sql(expression, "where") 3256 group = self.sql(expression, "group") 3257 aggregates = self.expressions(expression, key="aggregates") 3258 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3259 3260 if not (where or group or aggregates) and len(expression.expressions) == 1: 3261 return f"TTL {self.expressions(expression, flat=True)}" 3262 3263 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3264 3265 def transaction_sql(self, expression: exp.Transaction) -> str: 3266 return "BEGIN" 3267 3268 def commit_sql(self, expression: exp.Commit) -> str: 3269 chain = expression.args.get("chain") 3270 if chain is not None: 3271 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3272 3273 return f"COMMIT{chain or ''}" 3274 3275 def rollback_sql(self, expression: exp.Rollback) -> str: 3276 savepoint = expression.args.get("savepoint") 3277 savepoint = f" TO {savepoint}" if savepoint else "" 3278 return f"ROLLBACK{savepoint}" 3279 3280 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3281 this = self.sql(expression, "this") 3282 3283 dtype = self.sql(expression, "dtype") 3284 if dtype: 3285 collate = self.sql(expression, "collate") 3286 collate = f" COLLATE {collate}" if collate else "" 3287 using = self.sql(expression, "using") 3288 using = f" USING {using}" if using else "" 3289 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3290 3291 default = self.sql(expression, "default") 3292 if default: 3293 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3294 3295 comment = self.sql(expression, "comment") 3296 if comment: 3297 return f"ALTER COLUMN {this} COMMENT {comment}" 3298 3299 visible = expression.args.get("visible") 3300 if visible: 3301 return f"ALTER COLUMN {this} SET {visible}" 3302 3303 allow_null = expression.args.get("allow_null") 3304 drop = expression.args.get("drop") 3305 3306 if not drop and not allow_null: 3307 self.unsupported("Unsupported ALTER COLUMN syntax") 3308 3309 if allow_null is not None: 3310 keyword = "DROP" if drop else "SET" 3311 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3312 3313 return f"ALTER COLUMN {this} DROP DEFAULT" 3314 3315 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3316 this = self.sql(expression, "this") 3317 3318 visible = expression.args.get("visible") 3319 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3320 3321 return f"ALTER INDEX {this} {visible_sql}" 3322 3323 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3324 this = self.sql(expression, "this") 3325 if not isinstance(expression.this, exp.Var): 3326 this = f"KEY DISTKEY {this}" 3327 return f"ALTER DISTSTYLE {this}" 3328 3329 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3330 compound = " COMPOUND" if expression.args.get("compound") else "" 3331 this = self.sql(expression, "this") 3332 expressions = self.expressions(expression, flat=True) 3333 expressions = f"({expressions})" if expressions else "" 3334 return f"ALTER{compound} SORTKEY {this or expressions}" 3335 3336 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3337 if not self.RENAME_TABLE_WITH_DB: 3338 # Remove db from tables 3339 expression = expression.transform( 3340 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3341 ).assert_is(exp.AlterRename) 3342 this = self.sql(expression, "this") 3343 return f"RENAME TO {this}" 3344 3345 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3346 exists = " IF EXISTS" if expression.args.get("exists") else "" 3347 old_column = self.sql(expression, "this") 3348 new_column = self.sql(expression, "to") 3349 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3350 3351 def alterset_sql(self, expression: exp.AlterSet) -> str: 3352 exprs = self.expressions(expression, flat=True) 3353 return f"SET {exprs}" 3354 3355 def alter_sql(self, expression: exp.Alter) -> str: 3356 actions = expression.args["actions"] 3357 3358 if isinstance(actions[0], exp.ColumnDef): 3359 actions = self.add_column_sql(expression) 3360 elif isinstance(actions[0], exp.Schema): 3361 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3362 elif isinstance(actions[0], exp.Delete): 3363 actions = self.expressions(expression, key="actions", flat=True) 3364 elif isinstance(actions[0], exp.Query): 3365 actions = "AS " + self.expressions(expression, key="actions") 3366 else: 3367 actions = self.expressions(expression, key="actions", flat=True) 3368 3369 exists = " IF EXISTS" if expression.args.get("exists") else "" 3370 on_cluster = self.sql(expression, "cluster") 3371 on_cluster = f" {on_cluster}" if on_cluster else "" 3372 only = " ONLY" if expression.args.get("only") else "" 3373 options = self.expressions(expression, key="options") 3374 options = f", {options}" if options else "" 3375 kind = self.sql(expression, "kind") 3376 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3377 3378 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3379 3380 def add_column_sql(self, expression: exp.Alter) -> str: 3381 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3382 return self.expressions( 3383 expression, 3384 key="actions", 3385 prefix="ADD COLUMN ", 3386 skip_first=True, 3387 ) 3388 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3389 3390 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3391 expressions = self.expressions(expression) 3392 exists = " IF EXISTS " if expression.args.get("exists") else " " 3393 return f"DROP{exists}{expressions}" 3394 3395 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3396 return f"ADD {self.expressions(expression)}" 3397 3398 def distinct_sql(self, expression: exp.Distinct) -> str: 3399 this = self.expressions(expression, flat=True) 3400 3401 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3402 case = exp.case() 3403 for arg in expression.expressions: 3404 case = case.when(arg.is_(exp.null()), exp.null()) 3405 this = self.sql(case.else_(f"({this})")) 3406 3407 this = f" {this}" if this else "" 3408 3409 on = self.sql(expression, "on") 3410 on = f" ON {on}" if on else "" 3411 return f"DISTINCT{this}{on}" 3412 3413 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3414 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3415 3416 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3417 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3418 3419 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3420 this_sql = self.sql(expression, "this") 3421 expression_sql = self.sql(expression, "expression") 3422 kind = "MAX" if expression.args.get("max") else "MIN" 3423 return f"{this_sql} HAVING {kind} {expression_sql}" 3424 3425 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3426 return self.sql( 3427 exp.Cast( 3428 this=exp.Div(this=expression.this, expression=expression.expression), 3429 to=exp.DataType(this=exp.DataType.Type.INT), 3430 ) 3431 ) 3432 3433 def dpipe_sql(self, expression: exp.DPipe) -> str: 3434 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3435 return self.func( 3436 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3437 ) 3438 return self.binary(expression, "||") 3439 3440 def div_sql(self, expression: exp.Div) -> str: 3441 l, r = expression.left, expression.right 3442 3443 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3444 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3445 3446 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3447 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3448 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3449 3450 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3451 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3452 return self.sql( 3453 exp.cast( 3454 l / r, 3455 to=exp.DataType.Type.BIGINT, 3456 ) 3457 ) 3458 3459 return self.binary(expression, "/") 3460 3461 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3462 n = exp._wrap(expression.this, exp.Binary) 3463 d = exp._wrap(expression.expression, exp.Binary) 3464 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3465 3466 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3467 return self.binary(expression, "OVERLAPS") 3468 3469 def distance_sql(self, expression: exp.Distance) -> str: 3470 return self.binary(expression, "<->") 3471 3472 def dot_sql(self, expression: exp.Dot) -> str: 3473 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3474 3475 def eq_sql(self, expression: exp.EQ) -> str: 3476 return self.binary(expression, "=") 3477 3478 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3479 return self.binary(expression, ":=") 3480 3481 def escape_sql(self, expression: exp.Escape) -> str: 3482 return self.binary(expression, "ESCAPE") 3483 3484 def glob_sql(self, expression: exp.Glob) -> str: 3485 return self.binary(expression, "GLOB") 3486 3487 def gt_sql(self, expression: exp.GT) -> str: 3488 return self.binary(expression, ">") 3489 3490 def gte_sql(self, expression: exp.GTE) -> str: 3491 return self.binary(expression, ">=") 3492 3493 def ilike_sql(self, expression: exp.ILike) -> str: 3494 return self.binary(expression, "ILIKE") 3495 3496 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3497 return self.binary(expression, "ILIKE ANY") 3498 3499 def is_sql(self, expression: exp.Is) -> str: 3500 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3501 return self.sql( 3502 expression.this if expression.expression.this else exp.not_(expression.this) 3503 ) 3504 return self.binary(expression, "IS") 3505 3506 def like_sql(self, expression: exp.Like) -> str: 3507 return self.binary(expression, "LIKE") 3508 3509 def likeany_sql(self, expression: exp.LikeAny) -> str: 3510 return self.binary(expression, "LIKE ANY") 3511 3512 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3513 return self.binary(expression, "SIMILAR TO") 3514 3515 def lt_sql(self, expression: exp.LT) -> str: 3516 return self.binary(expression, "<") 3517 3518 def lte_sql(self, expression: exp.LTE) -> str: 3519 return self.binary(expression, "<=") 3520 3521 def mod_sql(self, expression: exp.Mod) -> str: 3522 return self.binary(expression, "%") 3523 3524 def mul_sql(self, expression: exp.Mul) -> str: 3525 return self.binary(expression, "*") 3526 3527 def neq_sql(self, expression: exp.NEQ) -> str: 3528 return self.binary(expression, "<>") 3529 3530 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3531 return self.binary(expression, "IS NOT DISTINCT FROM") 3532 3533 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3534 return self.binary(expression, "IS DISTINCT FROM") 3535 3536 def slice_sql(self, expression: exp.Slice) -> str: 3537 return self.binary(expression, ":") 3538 3539 def sub_sql(self, expression: exp.Sub) -> str: 3540 return self.binary(expression, "-") 3541 3542 def trycast_sql(self, expression: exp.TryCast) -> str: 3543 return self.cast_sql(expression, safe_prefix="TRY_") 3544 3545 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3546 return self.cast_sql(expression) 3547 3548 def try_sql(self, expression: exp.Try) -> str: 3549 if not self.TRY_SUPPORTED: 3550 self.unsupported("Unsupported TRY function") 3551 return self.sql(expression, "this") 3552 3553 return self.func("TRY", expression.this) 3554 3555 def log_sql(self, expression: exp.Log) -> str: 3556 this = expression.this 3557 expr = expression.expression 3558 3559 if self.dialect.LOG_BASE_FIRST is False: 3560 this, expr = expr, this 3561 elif self.dialect.LOG_BASE_FIRST is None and expr: 3562 if this.name in ("2", "10"): 3563 return self.func(f"LOG{this.name}", expr) 3564 3565 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3566 3567 return self.func("LOG", this, expr) 3568 3569 def use_sql(self, expression: exp.Use) -> str: 3570 kind = self.sql(expression, "kind") 3571 kind = f" {kind}" if kind else "" 3572 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3573 this = f" {this}" if this else "" 3574 return f"USE{kind}{this}" 3575 3576 def binary(self, expression: exp.Binary, op: str) -> str: 3577 sqls: t.List[str] = [] 3578 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3579 binary_type = type(expression) 3580 3581 while stack: 3582 node = stack.pop() 3583 3584 if type(node) is binary_type: 3585 op_func = node.args.get("operator") 3586 if op_func: 3587 op = f"OPERATOR({self.sql(op_func)})" 3588 3589 stack.append(node.right) 3590 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3591 stack.append(node.left) 3592 else: 3593 sqls.append(self.sql(node)) 3594 3595 return "".join(sqls) 3596 3597 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3598 to_clause = self.sql(expression, "to") 3599 if to_clause: 3600 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3601 3602 return self.function_fallback_sql(expression) 3603 3604 def function_fallback_sql(self, expression: exp.Func) -> str: 3605 args = [] 3606 3607 for key in expression.arg_types: 3608 arg_value = expression.args.get(key) 3609 3610 if isinstance(arg_value, list): 3611 for value in arg_value: 3612 args.append(value) 3613 elif arg_value is not None: 3614 args.append(arg_value) 3615 3616 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3617 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3618 else: 3619 name = expression.sql_name() 3620 3621 return self.func(name, *args) 3622 3623 def func( 3624 self, 3625 name: str, 3626 *args: t.Optional[exp.Expression | str], 3627 prefix: str = "(", 3628 suffix: str = ")", 3629 normalize: bool = True, 3630 ) -> str: 3631 name = self.normalize_func(name) if normalize else name 3632 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3633 3634 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3635 arg_sqls = tuple( 3636 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3637 ) 3638 if self.pretty and self.too_wide(arg_sqls): 3639 return self.indent( 3640 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3641 ) 3642 return sep.join(arg_sqls) 3643 3644 def too_wide(self, args: t.Iterable) -> bool: 3645 return sum(len(arg) for arg in args) > self.max_text_width 3646 3647 def format_time( 3648 self, 3649 expression: exp.Expression, 3650 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3651 inverse_time_trie: t.Optional[t.Dict] = None, 3652 ) -> t.Optional[str]: 3653 return format_time( 3654 self.sql(expression, "format"), 3655 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3656 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3657 ) 3658 3659 def expressions( 3660 self, 3661 expression: t.Optional[exp.Expression] = None, 3662 key: t.Optional[str] = None, 3663 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3664 flat: bool = False, 3665 indent: bool = True, 3666 skip_first: bool = False, 3667 skip_last: bool = False, 3668 sep: str = ", ", 3669 prefix: str = "", 3670 dynamic: bool = False, 3671 new_line: bool = False, 3672 ) -> str: 3673 expressions = expression.args.get(key or "expressions") if expression else sqls 3674 3675 if not expressions: 3676 return "" 3677 3678 if flat: 3679 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3680 3681 num_sqls = len(expressions) 3682 result_sqls = [] 3683 3684 for i, e in enumerate(expressions): 3685 sql = self.sql(e, comment=False) 3686 if not sql: 3687 continue 3688 3689 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3690 3691 if self.pretty: 3692 if self.leading_comma: 3693 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3694 else: 3695 result_sqls.append( 3696 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3697 ) 3698 else: 3699 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3700 3701 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3702 if new_line: 3703 result_sqls.insert(0, "") 3704 result_sqls.append("") 3705 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3706 else: 3707 result_sql = "".join(result_sqls) 3708 3709 return ( 3710 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3711 if indent 3712 else result_sql 3713 ) 3714 3715 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3716 flat = flat or isinstance(expression.parent, exp.Properties) 3717 expressions_sql = self.expressions(expression, flat=flat) 3718 if flat: 3719 return f"{op} {expressions_sql}" 3720 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3721 3722 def naked_property(self, expression: exp.Property) -> str: 3723 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3724 if not property_name: 3725 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3726 return f"{property_name} {self.sql(expression, 'this')}" 3727 3728 def tag_sql(self, expression: exp.Tag) -> str: 3729 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3730 3731 def token_sql(self, token_type: TokenType) -> str: 3732 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3733 3734 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3735 this = self.sql(expression, "this") 3736 expressions = self.no_identify(self.expressions, expression) 3737 expressions = ( 3738 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3739 ) 3740 return f"{this}{expressions}" if expressions.strip() != "" else this 3741 3742 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3743 this = self.sql(expression, "this") 3744 expressions = self.expressions(expression, flat=True) 3745 return f"{this}({expressions})" 3746 3747 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3748 return self.binary(expression, "=>") 3749 3750 def when_sql(self, expression: exp.When) -> str: 3751 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3752 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3753 condition = self.sql(expression, "condition") 3754 condition = f" AND {condition}" if condition else "" 3755 3756 then_expression = expression.args.get("then") 3757 if isinstance(then_expression, exp.Insert): 3758 this = self.sql(then_expression, "this") 3759 this = f"INSERT {this}" if this else "INSERT" 3760 then = self.sql(then_expression, "expression") 3761 then = f"{this} VALUES {then}" if then else this 3762 elif isinstance(then_expression, exp.Update): 3763 if isinstance(then_expression.args.get("expressions"), exp.Star): 3764 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3765 else: 3766 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3767 else: 3768 then = self.sql(then_expression) 3769 return f"WHEN {matched}{source}{condition} THEN {then}" 3770 3771 def whens_sql(self, expression: exp.Whens) -> str: 3772 return self.expressions(expression, sep=" ", indent=False) 3773 3774 def merge_sql(self, expression: exp.Merge) -> str: 3775 table = expression.this 3776 table_alias = "" 3777 3778 hints = table.args.get("hints") 3779 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3780 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3781 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3782 3783 this = self.sql(table) 3784 using = f"USING {self.sql(expression, 'using')}" 3785 on = f"ON {self.sql(expression, 'on')}" 3786 whens = self.sql(expression, "whens") 3787 3788 returning = self.sql(expression, "returning") 3789 if returning: 3790 whens = f"{whens}{returning}" 3791 3792 sep = self.sep() 3793 3794 return self.prepend_ctes( 3795 expression, 3796 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3797 ) 3798 3799 @unsupported_args("format") 3800 def tochar_sql(self, expression: exp.ToChar) -> str: 3801 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3802 3803 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3804 if not self.SUPPORTS_TO_NUMBER: 3805 self.unsupported("Unsupported TO_NUMBER function") 3806 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3807 3808 fmt = expression.args.get("format") 3809 if not fmt: 3810 self.unsupported("Conversion format is required for TO_NUMBER") 3811 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3812 3813 return self.func("TO_NUMBER", expression.this, fmt) 3814 3815 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3816 this = self.sql(expression, "this") 3817 kind = self.sql(expression, "kind") 3818 settings_sql = self.expressions(expression, key="settings", sep=" ") 3819 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3820 return f"{this}({kind}{args})" 3821 3822 def dictrange_sql(self, expression: exp.DictRange) -> str: 3823 this = self.sql(expression, "this") 3824 max = self.sql(expression, "max") 3825 min = self.sql(expression, "min") 3826 return f"{this}(MIN {min} MAX {max})" 3827 3828 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3829 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3830 3831 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3832 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3833 3834 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3835 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3836 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3837 3838 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3839 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3840 expressions = self.expressions(expression, flat=True) 3841 expressions = f" {self.wrap(expressions)}" if expressions else "" 3842 buckets = self.sql(expression, "buckets") 3843 kind = self.sql(expression, "kind") 3844 buckets = f" BUCKETS {buckets}" if buckets else "" 3845 order = self.sql(expression, "order") 3846 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3847 3848 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3849 return "" 3850 3851 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3852 expressions = self.expressions(expression, key="expressions", flat=True) 3853 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3854 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3855 buckets = self.sql(expression, "buckets") 3856 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3857 3858 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3859 this = self.sql(expression, "this") 3860 having = self.sql(expression, "having") 3861 3862 if having: 3863 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3864 3865 return self.func("ANY_VALUE", this) 3866 3867 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3868 transform = self.func("TRANSFORM", *expression.expressions) 3869 row_format_before = self.sql(expression, "row_format_before") 3870 row_format_before = f" {row_format_before}" if row_format_before else "" 3871 record_writer = self.sql(expression, "record_writer") 3872 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3873 using = f" USING {self.sql(expression, 'command_script')}" 3874 schema = self.sql(expression, "schema") 3875 schema = f" AS {schema}" if schema else "" 3876 row_format_after = self.sql(expression, "row_format_after") 3877 row_format_after = f" {row_format_after}" if row_format_after else "" 3878 record_reader = self.sql(expression, "record_reader") 3879 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3880 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3881 3882 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3883 key_block_size = self.sql(expression, "key_block_size") 3884 if key_block_size: 3885 return f"KEY_BLOCK_SIZE = {key_block_size}" 3886 3887 using = self.sql(expression, "using") 3888 if using: 3889 return f"USING {using}" 3890 3891 parser = self.sql(expression, "parser") 3892 if parser: 3893 return f"WITH PARSER {parser}" 3894 3895 comment = self.sql(expression, "comment") 3896 if comment: 3897 return f"COMMENT {comment}" 3898 3899 visible = expression.args.get("visible") 3900 if visible is not None: 3901 return "VISIBLE" if visible else "INVISIBLE" 3902 3903 engine_attr = self.sql(expression, "engine_attr") 3904 if engine_attr: 3905 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3906 3907 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3908 if secondary_engine_attr: 3909 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3910 3911 self.unsupported("Unsupported index constraint option.") 3912 return "" 3913 3914 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3915 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3916 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3917 3918 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3919 kind = self.sql(expression, "kind") 3920 kind = f"{kind} INDEX" if kind else "INDEX" 3921 this = self.sql(expression, "this") 3922 this = f" {this}" if this else "" 3923 index_type = self.sql(expression, "index_type") 3924 index_type = f" USING {index_type}" if index_type else "" 3925 expressions = self.expressions(expression, flat=True) 3926 expressions = f" ({expressions})" if expressions else "" 3927 options = self.expressions(expression, key="options", sep=" ") 3928 options = f" {options}" if options else "" 3929 return f"{kind}{this}{index_type}{expressions}{options}" 3930 3931 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3932 if self.NVL2_SUPPORTED: 3933 return self.function_fallback_sql(expression) 3934 3935 case = exp.Case().when( 3936 expression.this.is_(exp.null()).not_(copy=False), 3937 expression.args["true"], 3938 copy=False, 3939 ) 3940 else_cond = expression.args.get("false") 3941 if else_cond: 3942 case.else_(else_cond, copy=False) 3943 3944 return self.sql(case) 3945 3946 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3947 this = self.sql(expression, "this") 3948 expr = self.sql(expression, "expression") 3949 iterator = self.sql(expression, "iterator") 3950 condition = self.sql(expression, "condition") 3951 condition = f" IF {condition}" if condition else "" 3952 return f"{this} FOR {expr} IN {iterator}{condition}" 3953 3954 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3955 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3956 3957 def opclass_sql(self, expression: exp.Opclass) -> str: 3958 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3959 3960 def predict_sql(self, expression: exp.Predict) -> str: 3961 model = self.sql(expression, "this") 3962 model = f"MODEL {model}" 3963 table = self.sql(expression, "expression") 3964 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3965 parameters = self.sql(expression, "params_struct") 3966 return self.func("PREDICT", model, table, parameters or None) 3967 3968 def forin_sql(self, expression: exp.ForIn) -> str: 3969 this = self.sql(expression, "this") 3970 expression_sql = self.sql(expression, "expression") 3971 return f"FOR {this} DO {expression_sql}" 3972 3973 def refresh_sql(self, expression: exp.Refresh) -> str: 3974 this = self.sql(expression, "this") 3975 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3976 return f"REFRESH {table}{this}" 3977 3978 def toarray_sql(self, expression: exp.ToArray) -> str: 3979 arg = expression.this 3980 if not arg.type: 3981 from sqlglot.optimizer.annotate_types import annotate_types 3982 3983 arg = annotate_types(arg) 3984 3985 if arg.is_type(exp.DataType.Type.ARRAY): 3986 return self.sql(arg) 3987 3988 cond_for_null = arg.is_(exp.null()) 3989 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3990 3991 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3992 this = expression.this 3993 time_format = self.format_time(expression) 3994 3995 if time_format: 3996 return self.sql( 3997 exp.cast( 3998 exp.StrToTime(this=this, format=expression.args["format"]), 3999 exp.DataType.Type.TIME, 4000 ) 4001 ) 4002 4003 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4004 return self.sql(this) 4005 4006 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4007 4008 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4009 this = expression.this 4010 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4011 return self.sql(this) 4012 4013 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4014 4015 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4016 this = expression.this 4017 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4018 return self.sql(this) 4019 4020 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4021 4022 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4023 this = expression.this 4024 time_format = self.format_time(expression) 4025 4026 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4027 return self.sql( 4028 exp.cast( 4029 exp.StrToTime(this=this, format=expression.args["format"]), 4030 exp.DataType.Type.DATE, 4031 ) 4032 ) 4033 4034 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4035 return self.sql(this) 4036 4037 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4038 4039 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4040 return self.sql( 4041 exp.func( 4042 "DATEDIFF", 4043 expression.this, 4044 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4045 "day", 4046 ) 4047 ) 4048 4049 def lastday_sql(self, expression: exp.LastDay) -> str: 4050 if self.LAST_DAY_SUPPORTS_DATE_PART: 4051 return self.function_fallback_sql(expression) 4052 4053 unit = expression.text("unit") 4054 if unit and unit != "MONTH": 4055 self.unsupported("Date parts are not supported in LAST_DAY.") 4056 4057 return self.func("LAST_DAY", expression.this) 4058 4059 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4060 from sqlglot.dialects.dialect import unit_to_str 4061 4062 return self.func( 4063 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4064 ) 4065 4066 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4067 if self.CAN_IMPLEMENT_ARRAY_ANY: 4068 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4069 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4070 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4071 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4072 4073 from sqlglot.dialects import Dialect 4074 4075 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4076 if self.dialect.__class__ != Dialect: 4077 self.unsupported("ARRAY_ANY is unsupported") 4078 4079 return self.function_fallback_sql(expression) 4080 4081 def struct_sql(self, expression: exp.Struct) -> str: 4082 expression.set( 4083 "expressions", 4084 [ 4085 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4086 if isinstance(e, exp.PropertyEQ) 4087 else e 4088 for e in expression.expressions 4089 ], 4090 ) 4091 4092 return self.function_fallback_sql(expression) 4093 4094 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4095 low = self.sql(expression, "this") 4096 high = self.sql(expression, "expression") 4097 4098 return f"{low} TO {high}" 4099 4100 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4101 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4102 tables = f" {self.expressions(expression)}" 4103 4104 exists = " IF EXISTS" if expression.args.get("exists") else "" 4105 4106 on_cluster = self.sql(expression, "cluster") 4107 on_cluster = f" {on_cluster}" if on_cluster else "" 4108 4109 identity = self.sql(expression, "identity") 4110 identity = f" {identity} IDENTITY" if identity else "" 4111 4112 option = self.sql(expression, "option") 4113 option = f" {option}" if option else "" 4114 4115 partition = self.sql(expression, "partition") 4116 partition = f" {partition}" if partition else "" 4117 4118 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4119 4120 # This transpiles T-SQL's CONVERT function 4121 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4122 def convert_sql(self, expression: exp.Convert) -> str: 4123 to = expression.this 4124 value = expression.expression 4125 style = expression.args.get("style") 4126 safe = expression.args.get("safe") 4127 strict = expression.args.get("strict") 4128 4129 if not to or not value: 4130 return "" 4131 4132 # Retrieve length of datatype and override to default if not specified 4133 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4134 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4135 4136 transformed: t.Optional[exp.Expression] = None 4137 cast = exp.Cast if strict else exp.TryCast 4138 4139 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4140 if isinstance(style, exp.Literal) and style.is_int: 4141 from sqlglot.dialects.tsql import TSQL 4142 4143 style_value = style.name 4144 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4145 if not converted_style: 4146 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4147 4148 fmt = exp.Literal.string(converted_style) 4149 4150 if to.this == exp.DataType.Type.DATE: 4151 transformed = exp.StrToDate(this=value, format=fmt) 4152 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4153 transformed = exp.StrToTime(this=value, format=fmt) 4154 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4155 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4156 elif to.this == exp.DataType.Type.TEXT: 4157 transformed = exp.TimeToStr(this=value, format=fmt) 4158 4159 if not transformed: 4160 transformed = cast(this=value, to=to, safe=safe) 4161 4162 return self.sql(transformed) 4163 4164 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4165 this = expression.this 4166 if isinstance(this, exp.JSONPathWildcard): 4167 this = self.json_path_part(this) 4168 return f".{this}" if this else "" 4169 4170 if exp.SAFE_IDENTIFIER_RE.match(this): 4171 return f".{this}" 4172 4173 this = self.json_path_part(this) 4174 return ( 4175 f"[{this}]" 4176 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4177 else f".{this}" 4178 ) 4179 4180 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4181 this = self.json_path_part(expression.this) 4182 return f"[{this}]" if this else "" 4183 4184 def _simplify_unless_literal(self, expression: E) -> E: 4185 if not isinstance(expression, exp.Literal): 4186 from sqlglot.optimizer.simplify import simplify 4187 4188 expression = simplify(expression, dialect=self.dialect) 4189 4190 return expression 4191 4192 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4193 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4194 # The first modifier here will be the one closest to the AggFunc's arg 4195 mods = sorted( 4196 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4197 key=lambda x: 0 4198 if isinstance(x, exp.HavingMax) 4199 else (1 if isinstance(x, exp.Order) else 2), 4200 ) 4201 4202 if mods: 4203 mod = mods[0] 4204 this = expression.__class__(this=mod.this.copy()) 4205 this.meta["inline"] = True 4206 mod.this.replace(this) 4207 return self.sql(expression.this) 4208 4209 agg_func = expression.find(exp.AggFunc) 4210 4211 if agg_func: 4212 return self.sql(agg_func)[:-1] + f" {text})" 4213 4214 return f"{self.sql(expression, 'this')} {text}" 4215 4216 def _replace_line_breaks(self, string: str) -> str: 4217 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4218 if self.pretty: 4219 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4220 return string 4221 4222 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4223 option = self.sql(expression, "this") 4224 4225 if expression.expressions: 4226 upper = option.upper() 4227 4228 # Snowflake FILE_FORMAT options are separated by whitespace 4229 sep = " " if upper == "FILE_FORMAT" else ", " 4230 4231 # Databricks copy/format options do not set their list of values with EQ 4232 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4233 values = self.expressions(expression, flat=True, sep=sep) 4234 return f"{option}{op}({values})" 4235 4236 value = self.sql(expression, "expression") 4237 4238 if not value: 4239 return option 4240 4241 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4242 4243 return f"{option}{op}{value}" 4244 4245 def credentials_sql(self, expression: exp.Credentials) -> str: 4246 cred_expr = expression.args.get("credentials") 4247 if isinstance(cred_expr, exp.Literal): 4248 # Redshift case: CREDENTIALS <string> 4249 credentials = self.sql(expression, "credentials") 4250 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4251 else: 4252 # Snowflake case: CREDENTIALS = (...) 4253 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4254 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4255 4256 storage = self.sql(expression, "storage") 4257 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4258 4259 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4260 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4261 4262 iam_role = self.sql(expression, "iam_role") 4263 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4264 4265 region = self.sql(expression, "region") 4266 region = f" REGION {region}" if region else "" 4267 4268 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4269 4270 def copy_sql(self, expression: exp.Copy) -> str: 4271 this = self.sql(expression, "this") 4272 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4273 4274 credentials = self.sql(expression, "credentials") 4275 credentials = self.seg(credentials) if credentials else "" 4276 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4277 files = self.expressions(expression, key="files", flat=True) 4278 4279 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4280 params = self.expressions( 4281 expression, 4282 key="params", 4283 sep=sep, 4284 new_line=True, 4285 skip_last=True, 4286 skip_first=True, 4287 indent=self.COPY_PARAMS_ARE_WRAPPED, 4288 ) 4289 4290 if params: 4291 if self.COPY_PARAMS_ARE_WRAPPED: 4292 params = f" WITH ({params})" 4293 elif not self.pretty: 4294 params = f" {params}" 4295 4296 return f"COPY{this}{kind} {files}{credentials}{params}" 4297 4298 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4299 return "" 4300 4301 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4302 on_sql = "ON" if expression.args.get("on") else "OFF" 4303 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4304 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4305 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4306 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4307 4308 if filter_col or retention_period: 4309 on_sql = self.func("ON", filter_col, retention_period) 4310 4311 return f"DATA_DELETION={on_sql}" 4312 4313 def maskingpolicycolumnconstraint_sql( 4314 self, expression: exp.MaskingPolicyColumnConstraint 4315 ) -> str: 4316 this = self.sql(expression, "this") 4317 expressions = self.expressions(expression, flat=True) 4318 expressions = f" USING ({expressions})" if expressions else "" 4319 return f"MASKING POLICY {this}{expressions}" 4320 4321 def gapfill_sql(self, expression: exp.GapFill) -> str: 4322 this = self.sql(expression, "this") 4323 this = f"TABLE {this}" 4324 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4325 4326 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4327 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4328 4329 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4330 this = self.sql(expression, "this") 4331 expr = expression.expression 4332 4333 if isinstance(expr, exp.Func): 4334 # T-SQL's CLR functions are case sensitive 4335 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4336 else: 4337 expr = self.sql(expression, "expression") 4338 4339 return self.scope_resolution(expr, this) 4340 4341 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4342 if self.PARSE_JSON_NAME is None: 4343 return self.sql(expression.this) 4344 4345 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4346 4347 def rand_sql(self, expression: exp.Rand) -> str: 4348 lower = self.sql(expression, "lower") 4349 upper = self.sql(expression, "upper") 4350 4351 if lower and upper: 4352 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4353 return self.func("RAND", expression.this) 4354 4355 def changes_sql(self, expression: exp.Changes) -> str: 4356 information = self.sql(expression, "information") 4357 information = f"INFORMATION => {information}" 4358 at_before = self.sql(expression, "at_before") 4359 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4360 end = self.sql(expression, "end") 4361 end = f"{self.seg('')}{end}" if end else "" 4362 4363 return f"CHANGES ({information}){at_before}{end}" 4364 4365 def pad_sql(self, expression: exp.Pad) -> str: 4366 prefix = "L" if expression.args.get("is_left") else "R" 4367 4368 fill_pattern = self.sql(expression, "fill_pattern") or None 4369 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4370 fill_pattern = "' '" 4371 4372 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4373 4374 def summarize_sql(self, expression: exp.Summarize) -> str: 4375 table = " TABLE" if expression.args.get("table") else "" 4376 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4377 4378 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4379 generate_series = exp.GenerateSeries(**expression.args) 4380 4381 parent = expression.parent 4382 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4383 parent = parent.parent 4384 4385 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4386 return self.sql(exp.Unnest(expressions=[generate_series])) 4387 4388 if isinstance(parent, exp.Select): 4389 self.unsupported("GenerateSeries projection unnesting is not supported.") 4390 4391 return self.sql(generate_series) 4392 4393 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4394 exprs = expression.expressions 4395 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4396 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4397 else: 4398 rhs = self.expressions(expression) 4399 4400 return self.func(name, expression.this, rhs or None) 4401 4402 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4403 if self.SUPPORTS_CONVERT_TIMEZONE: 4404 return self.function_fallback_sql(expression) 4405 4406 source_tz = expression.args.get("source_tz") 4407 target_tz = expression.args.get("target_tz") 4408 timestamp = expression.args.get("timestamp") 4409 4410 if source_tz and timestamp: 4411 timestamp = exp.AtTimeZone( 4412 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4413 ) 4414 4415 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4416 4417 return self.sql(expr) 4418 4419 def json_sql(self, expression: exp.JSON) -> str: 4420 this = self.sql(expression, "this") 4421 this = f" {this}" if this else "" 4422 4423 _with = expression.args.get("with") 4424 4425 if _with is None: 4426 with_sql = "" 4427 elif not _with: 4428 with_sql = " WITHOUT" 4429 else: 4430 with_sql = " WITH" 4431 4432 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4433 4434 return f"JSON{this}{with_sql}{unique_sql}" 4435 4436 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4437 def _generate_on_options(arg: t.Any) -> str: 4438 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4439 4440 path = self.sql(expression, "path") 4441 returning = self.sql(expression, "returning") 4442 returning = f" RETURNING {returning}" if returning else "" 4443 4444 on_condition = self.sql(expression, "on_condition") 4445 on_condition = f" {on_condition}" if on_condition else "" 4446 4447 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4448 4449 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4450 else_ = "ELSE " if expression.args.get("else_") else "" 4451 condition = self.sql(expression, "expression") 4452 condition = f"WHEN {condition} THEN " if condition else else_ 4453 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4454 return f"{condition}{insert}" 4455 4456 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4457 kind = self.sql(expression, "kind") 4458 expressions = self.seg(self.expressions(expression, sep=" ")) 4459 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4460 return res 4461 4462 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4463 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4464 empty = expression.args.get("empty") 4465 empty = ( 4466 f"DEFAULT {empty} ON EMPTY" 4467 if isinstance(empty, exp.Expression) 4468 else self.sql(expression, "empty") 4469 ) 4470 4471 error = expression.args.get("error") 4472 error = ( 4473 f"DEFAULT {error} ON ERROR" 4474 if isinstance(error, exp.Expression) 4475 else self.sql(expression, "error") 4476 ) 4477 4478 if error and empty: 4479 error = ( 4480 f"{empty} {error}" 4481 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4482 else f"{error} {empty}" 4483 ) 4484 empty = "" 4485 4486 null = self.sql(expression, "null") 4487 4488 return f"{empty}{error}{null}" 4489 4490 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4491 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4492 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4493 4494 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4495 this = self.sql(expression, "this") 4496 path = self.sql(expression, "path") 4497 4498 passing = self.expressions(expression, "passing") 4499 passing = f" PASSING {passing}" if passing else "" 4500 4501 on_condition = self.sql(expression, "on_condition") 4502 on_condition = f" {on_condition}" if on_condition else "" 4503 4504 path = f"{path}{passing}{on_condition}" 4505 4506 return self.func("JSON_EXISTS", this, path) 4507 4508 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4509 array_agg = self.function_fallback_sql(expression) 4510 4511 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4512 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4513 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4514 parent = expression.parent 4515 if isinstance(parent, exp.Filter): 4516 parent_cond = parent.expression.this 4517 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4518 else: 4519 this = expression.this 4520 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4521 if this.find(exp.Column): 4522 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4523 this_sql = ( 4524 self.expressions(this) 4525 if isinstance(this, exp.Distinct) 4526 else self.sql(expression, "this") 4527 ) 4528 4529 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4530 4531 return array_agg 4532 4533 def apply_sql(self, expression: exp.Apply) -> str: 4534 this = self.sql(expression, "this") 4535 expr = self.sql(expression, "expression") 4536 4537 return f"{this} APPLY({expr})" 4538 4539 def grant_sql(self, expression: exp.Grant) -> str: 4540 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4541 4542 kind = self.sql(expression, "kind") 4543 kind = f" {kind}" if kind else "" 4544 4545 securable = self.sql(expression, "securable") 4546 securable = f" {securable}" if securable else "" 4547 4548 principals = self.expressions(expression, key="principals", flat=True) 4549 4550 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4551 4552 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4553 4554 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4555 this = self.sql(expression, "this") 4556 columns = self.expressions(expression, flat=True) 4557 columns = f"({columns})" if columns else "" 4558 4559 return f"{this}{columns}" 4560 4561 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4562 this = self.sql(expression, "this") 4563 4564 kind = self.sql(expression, "kind") 4565 kind = f"{kind} " if kind else "" 4566 4567 return f"{kind}{this}" 4568 4569 def columns_sql(self, expression: exp.Columns): 4570 func = self.function_fallback_sql(expression) 4571 if expression.args.get("unpack"): 4572 func = f"*{func}" 4573 4574 return func 4575 4576 def overlay_sql(self, expression: exp.Overlay): 4577 this = self.sql(expression, "this") 4578 expr = self.sql(expression, "expression") 4579 from_sql = self.sql(expression, "from") 4580 for_sql = self.sql(expression, "for") 4581 for_sql = f" FOR {for_sql}" if for_sql else "" 4582 4583 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4584 4585 @unsupported_args("format") 4586 def todouble_sql(self, expression: exp.ToDouble) -> str: 4587 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4588 4589 def string_sql(self, expression: exp.String) -> str: 4590 this = expression.this 4591 zone = expression.args.get("zone") 4592 4593 if zone: 4594 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4595 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4596 # set for source_tz to transpile the time conversion before the STRING cast 4597 this = exp.ConvertTimezone( 4598 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4599 ) 4600 4601 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4602 4603 def median_sql(self, expression: exp.Median): 4604 if not self.SUPPORTS_MEDIAN: 4605 return self.sql( 4606 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4607 ) 4608 4609 return self.function_fallback_sql(expression) 4610 4611 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4612 filler = self.sql(expression, "this") 4613 filler = f" {filler}" if filler else "" 4614 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4615 return f"TRUNCATE{filler} {with_count}" 4616 4617 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4618 if self.SUPPORTS_UNIX_SECONDS: 4619 return self.function_fallback_sql(expression) 4620 4621 start_ts = exp.cast( 4622 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4623 ) 4624 4625 return self.sql( 4626 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4627 ) 4628 4629 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4630 dim = expression.expression 4631 4632 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4633 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4634 if not (dim.is_int and dim.name == "1"): 4635 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4636 dim = None 4637 4638 # If dimension is required but not specified, default initialize it 4639 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4640 dim = exp.Literal.number(1) 4641 4642 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4643 4644 def attach_sql(self, expression: exp.Attach) -> str: 4645 this = self.sql(expression, "this") 4646 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4647 expressions = self.expressions(expression) 4648 expressions = f" ({expressions})" if expressions else "" 4649 4650 return f"ATTACH{exists_sql} {this}{expressions}" 4651 4652 def detach_sql(self, expression: exp.Detach) -> str: 4653 this = self.sql(expression, "this") 4654 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4655 4656 return f"DETACH{exists_sql} {this}" 4657 4658 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4659 this = self.sql(expression, "this") 4660 value = self.sql(expression, "expression") 4661 value = f" {value}" if value else "" 4662 return f"{this}{value}" 4663 4664 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4665 this_sql = self.sql(expression, "this") 4666 if isinstance(expression.this, exp.Table): 4667 this_sql = f"TABLE {this_sql}" 4668 4669 return self.func( 4670 "FEATURES_AT_TIME", 4671 this_sql, 4672 expression.args.get("time"), 4673 expression.args.get("num_rows"), 4674 expression.args.get("ignore_feature_nulls"), 4675 ) 4676 4677 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4678 return ( 4679 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4680 ) 4681 4682 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4683 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4684 encode = f"{encode} {self.sql(expression, 'this')}" 4685 4686 properties = expression.args.get("properties") 4687 if properties: 4688 encode = f"{encode} {self.properties(properties)}" 4689 4690 return encode 4691 4692 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4693 this = self.sql(expression, "this") 4694 include = f"INCLUDE {this}" 4695 4696 column_def = self.sql(expression, "column_def") 4697 if column_def: 4698 include = f"{include} {column_def}" 4699 4700 alias = self.sql(expression, "alias") 4701 if alias: 4702 include = f"{include} AS {alias}" 4703 4704 return include 4705 4706 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4707 name = f"NAME {self.sql(expression, 'this')}" 4708 return self.func("XMLELEMENT", name, *expression.expressions) 4709 4710 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4711 partitions = self.expressions(expression, "partition_expressions") 4712 create = self.expressions(expression, "create_expressions") 4713 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4714 4715 def partitionbyrangepropertydynamic_sql( 4716 self, expression: exp.PartitionByRangePropertyDynamic 4717 ) -> str: 4718 start = self.sql(expression, "start") 4719 end = self.sql(expression, "end") 4720 4721 every = expression.args["every"] 4722 if isinstance(every, exp.Interval) and every.this.is_string: 4723 every.this.replace(exp.Literal.number(every.name)) 4724 4725 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4726 4727 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4728 name = self.sql(expression, "this") 4729 values = self.expressions(expression, flat=True) 4730 4731 return f"NAME {name} VALUE {values}" 4732 4733 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4734 kind = self.sql(expression, "kind") 4735 sample = self.sql(expression, "sample") 4736 return f"SAMPLE {sample} {kind}" 4737 4738 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4739 kind = self.sql(expression, "kind") 4740 option = self.sql(expression, "option") 4741 option = f" {option}" if option else "" 4742 this = self.sql(expression, "this") 4743 this = f" {this}" if this else "" 4744 columns = self.expressions(expression) 4745 columns = f" {columns}" if columns else "" 4746 return f"{kind}{option} STATISTICS{this}{columns}" 4747 4748 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4749 this = self.sql(expression, "this") 4750 columns = self.expressions(expression) 4751 inner_expression = self.sql(expression, "expression") 4752 inner_expression = f" {inner_expression}" if inner_expression else "" 4753 update_options = self.sql(expression, "update_options") 4754 update_options = f" {update_options} UPDATE" if update_options else "" 4755 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4756 4757 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4758 kind = self.sql(expression, "kind") 4759 kind = f" {kind}" if kind else "" 4760 return f"DELETE{kind} STATISTICS" 4761 4762 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4763 inner_expression = self.sql(expression, "expression") 4764 return f"LIST CHAINED ROWS{inner_expression}" 4765 4766 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4767 kind = self.sql(expression, "kind") 4768 this = self.sql(expression, "this") 4769 this = f" {this}" if this else "" 4770 inner_expression = self.sql(expression, "expression") 4771 return f"VALIDATE {kind}{this}{inner_expression}" 4772 4773 def analyze_sql(self, expression: exp.Analyze) -> str: 4774 options = self.expressions(expression, key="options", sep=" ") 4775 options = f" {options}" if options else "" 4776 kind = self.sql(expression, "kind") 4777 kind = f" {kind}" if kind else "" 4778 this = self.sql(expression, "this") 4779 this = f" {this}" if this else "" 4780 mode = self.sql(expression, "mode") 4781 mode = f" {mode}" if mode else "" 4782 properties = self.sql(expression, "properties") 4783 properties = f" {properties}" if properties else "" 4784 partition = self.sql(expression, "partition") 4785 partition = f" {partition}" if partition else "" 4786 inner_expression = self.sql(expression, "expression") 4787 inner_expression = f" {inner_expression}" if inner_expression else "" 4788 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4789 4790 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4791 this = self.sql(expression, "this") 4792 namespaces = self.expressions(expression, key="namespaces") 4793 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4794 passing = self.expressions(expression, key="passing") 4795 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4796 columns = self.expressions(expression, key="columns") 4797 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4798 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4799 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4800 4801 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4802 this = self.sql(expression, "this") 4803 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4804 4805 def export_sql(self, expression: exp.Export) -> str: 4806 this = self.sql(expression, "this") 4807 connection = self.sql(expression, "connection") 4808 connection = f"WITH CONNECTION {connection} " if connection else "" 4809 options = self.sql(expression, "options") 4810 return f"EXPORT DATA {connection}{options} AS {this}" 4811 4812 def declare_sql(self, expression: exp.Declare) -> str: 4813 return f"DECLARE {self.expressions(expression, flat=True)}" 4814 4815 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4816 variable = self.sql(expression, "this") 4817 default = self.sql(expression, "default") 4818 default = f" = {default}" if default else "" 4819 4820 kind = self.sql(expression, "kind") 4821 if isinstance(expression.args.get("kind"), exp.Schema): 4822 kind = f"TABLE {kind}" 4823 4824 return f"{variable} AS {kind}{default}" 4825 4826 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4827 kind = self.sql(expression, "kind") 4828 this = self.sql(expression, "this") 4829 set = self.sql(expression, "expression") 4830 using = self.sql(expression, "using") 4831 using = f" USING {using}" if using else "" 4832 4833 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4834 4835 return f"{kind_sql} {this} SET {set}{using}" 4836 4837 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4838 params = self.expressions(expression, key="params", flat=True) 4839 return self.func(expression.name, *expression.expressions) + f"({params})" 4840 4841 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4842 return self.func(expression.name, *expression.expressions) 4843 4844 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4845 return self.anonymousaggfunc_sql(expression) 4846 4847 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4848 return self.parameterizedagg_sql(expression) 4849 4850 def show_sql(self, expression: exp.Show) -> str: 4851 self.unsupported("Unsupported SHOW statement") 4852 return "" 4853 4854 def put_sql(self, expression: exp.Put) -> str: 4855 props = expression.args.get("properties") 4856 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4857 this = self.sql(expression, "this") 4858 target = self.sql(expression, "target") 4859 return f"PUT {this} {target}{props_sql}"
logger =
<Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE =
re.compile('\\\\(\\d+)')
UNSUPPORTED_TEMPLATE =
"Argument '{}' is not supported for expression '{}' when targeting {}."
def
unsupported_args( *args: Union[str, Tuple[str, str]]) -> Callable[[Callable[[~G, ~E], str]], Callable[[~G, ~E], str]]:
30def unsupported_args( 31 *args: t.Union[str, t.Tuple[str, str]], 32) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 33 """ 34 Decorator that can be used to mark certain args of an `Expression` subclass as unsupported. 35 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 36 """ 37 diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {} 38 for arg in args: 39 if isinstance(arg, str): 40 diagnostic_by_arg[arg] = None 41 else: 42 diagnostic_by_arg[arg[0]] = arg[1] 43 44 def decorator(func: GeneratorMethod) -> GeneratorMethod: 45 @wraps(func) 46 def _func(generator: G, expression: E) -> str: 47 expression_name = expression.__class__.__name__ 48 dialect_name = generator.dialect.__class__.__name__ 49 50 for arg_name, diagnostic in diagnostic_by_arg.items(): 51 if expression.args.get(arg_name): 52 diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format( 53 arg_name, expression_name, dialect_name 54 ) 55 generator.unsupported(diagnostic) 56 57 return func(generator, expression) 58 59 return _func 60 61 return decorator
Decorator that can be used to mark certain args of an Expression subclass as unsupported.
It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
class
Generator:
75class Generator(metaclass=_Generator): 76 """ 77 Generator converts a given syntax tree to the corresponding SQL string. 78 79 Args: 80 pretty: Whether to format the produced SQL string. 81 Default: False. 82 identify: Determines when an identifier should be quoted. Possible values are: 83 False (default): Never quote, except in cases where it's mandatory by the dialect. 84 True or 'always': Always quote. 85 'safe': Only quote identifiers that are case insensitive. 86 normalize: Whether to normalize identifiers to lowercase. 87 Default: False. 88 pad: The pad size in a formatted string. For example, this affects the indentation of 89 a projection in a query, relative to its nesting level. 90 Default: 2. 91 indent: The indentation size in a formatted string. For example, this affects the 92 indentation of subqueries and filters under a `WHERE` clause. 93 Default: 2. 94 normalize_functions: How to normalize function names. Possible values are: 95 "upper" or True (default): Convert names to uppercase. 96 "lower": Convert names to lowercase. 97 False: Disables function name normalization. 98 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 99 Default ErrorLevel.WARN. 100 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 101 This is only relevant if unsupported_level is ErrorLevel.RAISE. 102 Default: 3 103 leading_comma: Whether the comma is leading or trailing in select expressions. 104 This is only relevant when generating in pretty mode. 105 Default: False 106 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 107 The default is on the smaller end because the length only represents a segment and not the true 108 line length. 109 Default: 80 110 comments: Whether to preserve comments in the output SQL code. 111 Default: True 112 """ 113 114 TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = { 115 **JSON_PATH_PART_TRANSFORMS, 116 exp.AllowedValuesProperty: lambda self, 117 e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}", 118 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 119 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 120 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 121 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 122 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 123 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 124 exp.CaseSpecificColumnConstraint: lambda _, 125 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 126 exp.Ceil: lambda self, e: self.ceil_floor(e), 127 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 128 exp.CharacterSetProperty: lambda self, 129 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 130 exp.ClusteredColumnConstraint: lambda self, 131 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 132 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 133 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 134 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 135 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 136 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 137 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 138 exp.DynamicProperty: lambda *_: "DYNAMIC", 139 exp.EmptyProperty: lambda *_: "EMPTY", 140 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 141 exp.EphemeralColumnConstraint: lambda self, 142 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 143 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 144 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 145 exp.Except: lambda self, e: self.set_operations(e), 146 exp.ExternalProperty: lambda *_: "EXTERNAL", 147 exp.Floor: lambda self, e: self.ceil_floor(e), 148 exp.GlobalProperty: lambda *_: "GLOBAL", 149 exp.HeapProperty: lambda *_: "HEAP", 150 exp.IcebergProperty: lambda *_: "ICEBERG", 151 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 152 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 153 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 154 exp.Intersect: lambda self, e: self.set_operations(e), 155 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 156 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 157 exp.LanguageProperty: lambda self, e: self.naked_property(e), 158 exp.LocationProperty: lambda self, e: self.naked_property(e), 159 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 160 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 161 exp.NonClusteredColumnConstraint: lambda self, 162 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 163 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 164 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 165 exp.OnCommitProperty: lambda _, 166 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 167 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 168 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 169 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 170 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 171 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 172 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 173 exp.ProjectionPolicyColumnConstraint: lambda self, 174 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 175 exp.RemoteWithConnectionModelProperty: lambda self, 176 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 177 exp.ReturnsProperty: lambda self, e: ( 178 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 179 ), 180 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 181 exp.SecureProperty: lambda *_: "SECURE", 182 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 183 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 184 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 185 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 186 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 187 exp.SqlReadWriteProperty: lambda _, e: e.name, 188 exp.SqlSecurityProperty: lambda _, 189 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 190 exp.StabilityProperty: lambda _, e: e.name, 191 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 192 exp.StreamingTableProperty: lambda *_: "STREAMING", 193 exp.StrictProperty: lambda *_: "STRICT", 194 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 195 exp.TemporaryProperty: lambda *_: "TEMPORARY", 196 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 197 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 198 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 199 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 200 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 201 exp.TransientProperty: lambda *_: "TRANSIENT", 202 exp.Union: lambda self, e: self.set_operations(e), 203 exp.UnloggedProperty: lambda *_: "UNLOGGED", 204 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 205 exp.Uuid: lambda *_: "UUID()", 206 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 207 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 208 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 209 exp.VolatileProperty: lambda *_: "VOLATILE", 210 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 211 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 212 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 213 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 214 exp.ForceProperty: lambda *_: "FORCE", 215 } 216 217 # Whether null ordering is supported in order by 218 # True: Full Support, None: No support, False: No support for certain cases 219 # such as window specifications, aggregate functions etc 220 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 221 222 # Whether ignore nulls is inside the agg or outside. 223 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 224 IGNORE_NULLS_IN_FUNC = False 225 226 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 227 LOCKING_READS_SUPPORTED = False 228 229 # Whether the EXCEPT and INTERSECT operations can return duplicates 230 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 231 232 # Wrap derived values in parens, usually standard but spark doesn't support it 233 WRAP_DERIVED_VALUES = True 234 235 # Whether create function uses an AS before the RETURN 236 CREATE_FUNCTION_RETURN_AS = True 237 238 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 239 MATCHED_BY_SOURCE = True 240 241 # Whether the INTERVAL expression works only with values like '1 day' 242 SINGLE_STRING_INTERVAL = False 243 244 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 245 INTERVAL_ALLOWS_PLURAL_FORM = True 246 247 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 248 LIMIT_FETCH = "ALL" 249 250 # Whether limit and fetch allows expresions or just limits 251 LIMIT_ONLY_LITERALS = False 252 253 # Whether a table is allowed to be renamed with a db 254 RENAME_TABLE_WITH_DB = True 255 256 # The separator for grouping sets and rollups 257 GROUPINGS_SEP = "," 258 259 # The string used for creating an index on a table 260 INDEX_ON = "ON" 261 262 # Whether join hints should be generated 263 JOIN_HINTS = True 264 265 # Whether table hints should be generated 266 TABLE_HINTS = True 267 268 # Whether query hints should be generated 269 QUERY_HINTS = True 270 271 # What kind of separator to use for query hints 272 QUERY_HINT_SEP = ", " 273 274 # Whether comparing against booleans (e.g. x IS TRUE) is supported 275 IS_BOOL_ALLOWED = True 276 277 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 278 DUPLICATE_KEY_UPDATE_WITH_SET = True 279 280 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 281 LIMIT_IS_TOP = False 282 283 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 284 RETURNING_END = True 285 286 # Whether to generate an unquoted value for EXTRACT's date part argument 287 EXTRACT_ALLOWS_QUOTES = True 288 289 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 290 TZ_TO_WITH_TIME_ZONE = False 291 292 # Whether the NVL2 function is supported 293 NVL2_SUPPORTED = True 294 295 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 296 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 297 298 # Whether VALUES statements can be used as derived tables. 299 # MySQL 5 and Redshift do not allow this, so when False, it will convert 300 # SELECT * VALUES into SELECT UNION 301 VALUES_AS_TABLE = True 302 303 # Whether the word COLUMN is included when adding a column with ALTER TABLE 304 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 305 306 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 307 UNNEST_WITH_ORDINALITY = True 308 309 # Whether FILTER (WHERE cond) can be used for conditional aggregation 310 AGGREGATE_FILTER_SUPPORTED = True 311 312 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 313 SEMI_ANTI_JOIN_WITH_SIDE = True 314 315 # Whether to include the type of a computed column in the CREATE DDL 316 COMPUTED_COLUMN_WITH_TYPE = True 317 318 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 319 SUPPORTS_TABLE_COPY = True 320 321 # Whether parentheses are required around the table sample's expression 322 TABLESAMPLE_REQUIRES_PARENS = True 323 324 # Whether a table sample clause's size needs to be followed by the ROWS keyword 325 TABLESAMPLE_SIZE_IS_ROWS = True 326 327 # The keyword(s) to use when generating a sample clause 328 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 329 330 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 331 TABLESAMPLE_WITH_METHOD = True 332 333 # The keyword to use when specifying the seed of a sample clause 334 TABLESAMPLE_SEED_KEYWORD = "SEED" 335 336 # Whether COLLATE is a function instead of a binary operator 337 COLLATE_IS_FUNC = False 338 339 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 340 DATA_TYPE_SPECIFIERS_ALLOWED = False 341 342 # Whether conditions require booleans WHERE x = 0 vs WHERE x 343 ENSURE_BOOLS = False 344 345 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 346 CTE_RECURSIVE_KEYWORD_REQUIRED = True 347 348 # Whether CONCAT requires >1 arguments 349 SUPPORTS_SINGLE_ARG_CONCAT = True 350 351 # Whether LAST_DAY function supports a date part argument 352 LAST_DAY_SUPPORTS_DATE_PART = True 353 354 # Whether named columns are allowed in table aliases 355 SUPPORTS_TABLE_ALIAS_COLUMNS = True 356 357 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 358 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 359 360 # What delimiter to use for separating JSON key/value pairs 361 JSON_KEY_VALUE_PAIR_SEP = ":" 362 363 # INSERT OVERWRITE TABLE x override 364 INSERT_OVERWRITE = " OVERWRITE TABLE" 365 366 # Whether the SELECT .. INTO syntax is used instead of CTAS 367 SUPPORTS_SELECT_INTO = False 368 369 # Whether UNLOGGED tables can be created 370 SUPPORTS_UNLOGGED_TABLES = False 371 372 # Whether the CREATE TABLE LIKE statement is supported 373 SUPPORTS_CREATE_TABLE_LIKE = True 374 375 # Whether the LikeProperty needs to be specified inside of the schema clause 376 LIKE_PROPERTY_INSIDE_SCHEMA = False 377 378 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 379 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 380 MULTI_ARG_DISTINCT = True 381 382 # Whether the JSON extraction operators expect a value of type JSON 383 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 384 385 # Whether bracketed keys like ["foo"] are supported in JSON paths 386 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 387 388 # Whether to escape keys using single quotes in JSON paths 389 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 390 391 # The JSONPathPart expressions supported by this dialect 392 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 393 394 # Whether any(f(x) for x in array) can be implemented by this dialect 395 CAN_IMPLEMENT_ARRAY_ANY = False 396 397 # Whether the function TO_NUMBER is supported 398 SUPPORTS_TO_NUMBER = True 399 400 # Whether or not set op modifiers apply to the outer set op or select. 401 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 402 # True means limit 1 happens after the set op, False means it it happens on y. 403 SET_OP_MODIFIERS = True 404 405 # Whether parameters from COPY statement are wrapped in parentheses 406 COPY_PARAMS_ARE_WRAPPED = True 407 408 # Whether values of params are set with "=" token or empty space 409 COPY_PARAMS_EQ_REQUIRED = False 410 411 # Whether COPY statement has INTO keyword 412 COPY_HAS_INTO_KEYWORD = True 413 414 # Whether the conditional TRY(expression) function is supported 415 TRY_SUPPORTED = True 416 417 # Whether the UESCAPE syntax in unicode strings is supported 418 SUPPORTS_UESCAPE = True 419 420 # The keyword to use when generating a star projection with excluded columns 421 STAR_EXCEPT = "EXCEPT" 422 423 # The HEX function name 424 HEX_FUNC = "HEX" 425 426 # The keywords to use when prefixing & separating WITH based properties 427 WITH_PROPERTIES_PREFIX = "WITH" 428 429 # Whether to quote the generated expression of exp.JsonPath 430 QUOTE_JSON_PATH = True 431 432 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 433 PAD_FILL_PATTERN_IS_REQUIRED = False 434 435 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 436 SUPPORTS_EXPLODING_PROJECTIONS = True 437 438 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 439 ARRAY_CONCAT_IS_VAR_LEN = True 440 441 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 442 SUPPORTS_CONVERT_TIMEZONE = False 443 444 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 445 SUPPORTS_MEDIAN = True 446 447 # Whether UNIX_SECONDS(timestamp) is supported 448 SUPPORTS_UNIX_SECONDS = False 449 450 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 451 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 452 453 # The function name of the exp.ArraySize expression 454 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 455 456 # The syntax to use when altering the type of a column 457 ALTER_SET_TYPE = "SET DATA TYPE" 458 459 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 460 # None -> Doesn't support it at all 461 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 462 # True (Postgres) -> Explicitly requires it 463 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 464 465 TYPE_MAPPING = { 466 exp.DataType.Type.DATETIME2: "TIMESTAMP", 467 exp.DataType.Type.NCHAR: "CHAR", 468 exp.DataType.Type.NVARCHAR: "VARCHAR", 469 exp.DataType.Type.MEDIUMTEXT: "TEXT", 470 exp.DataType.Type.LONGTEXT: "TEXT", 471 exp.DataType.Type.TINYTEXT: "TEXT", 472 exp.DataType.Type.BLOB: "VARBINARY", 473 exp.DataType.Type.MEDIUMBLOB: "BLOB", 474 exp.DataType.Type.LONGBLOB: "BLOB", 475 exp.DataType.Type.TINYBLOB: "BLOB", 476 exp.DataType.Type.INET: "INET", 477 exp.DataType.Type.ROWVERSION: "VARBINARY", 478 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 479 } 480 481 TIME_PART_SINGULARS = { 482 "MICROSECONDS": "MICROSECOND", 483 "SECONDS": "SECOND", 484 "MINUTES": "MINUTE", 485 "HOURS": "HOUR", 486 "DAYS": "DAY", 487 "WEEKS": "WEEK", 488 "MONTHS": "MONTH", 489 "QUARTERS": "QUARTER", 490 "YEARS": "YEAR", 491 } 492 493 AFTER_HAVING_MODIFIER_TRANSFORMS = { 494 "cluster": lambda self, e: self.sql(e, "cluster"), 495 "distribute": lambda self, e: self.sql(e, "distribute"), 496 "sort": lambda self, e: self.sql(e, "sort"), 497 "windows": lambda self, e: ( 498 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 499 if e.args.get("windows") 500 else "" 501 ), 502 "qualify": lambda self, e: self.sql(e, "qualify"), 503 } 504 505 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 506 507 STRUCT_DELIMITER = ("<", ">") 508 509 PARAMETER_TOKEN = "@" 510 NAMED_PLACEHOLDER_TOKEN = ":" 511 512 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 513 514 PROPERTIES_LOCATION = { 515 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 516 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 517 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 518 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 520 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 521 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 523 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 525 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 526 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 527 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 528 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 529 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 530 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 531 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 532 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 533 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 534 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 535 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 537 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 538 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 539 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 540 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 541 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 542 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 543 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 544 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 545 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 546 exp.HeapProperty: exp.Properties.Location.POST_WITH, 547 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 548 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 549 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 552 exp.JournalProperty: exp.Properties.Location.POST_NAME, 553 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 556 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 557 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 558 exp.LogProperty: exp.Properties.Location.POST_NAME, 559 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 560 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 561 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 562 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 563 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 564 exp.Order: exp.Properties.Location.POST_SCHEMA, 565 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 566 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 567 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 568 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 569 exp.Property: exp.Properties.Location.POST_WITH, 570 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 575 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 576 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 577 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 578 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 579 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 580 exp.Set: exp.Properties.Location.POST_SCHEMA, 581 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 582 exp.SetProperty: exp.Properties.Location.POST_CREATE, 583 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 584 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 585 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 586 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 587 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 588 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 589 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 591 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 592 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 593 exp.Tags: exp.Properties.Location.POST_WITH, 594 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 595 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 596 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 597 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 598 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 599 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 600 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 601 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 602 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 603 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 604 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 605 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 606 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 607 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 608 } 609 610 # Keywords that can't be used as unquoted identifier names 611 RESERVED_KEYWORDS: t.Set[str] = set() 612 613 # Expressions whose comments are separated from them for better formatting 614 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 615 exp.Command, 616 exp.Create, 617 exp.Describe, 618 exp.Delete, 619 exp.Drop, 620 exp.From, 621 exp.Insert, 622 exp.Join, 623 exp.MultitableInserts, 624 exp.Select, 625 exp.SetOperation, 626 exp.Update, 627 exp.Where, 628 exp.With, 629 ) 630 631 # Expressions that should not have their comments generated in maybe_comment 632 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 633 exp.Binary, 634 exp.SetOperation, 635 ) 636 637 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 638 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 639 exp.Column, 640 exp.Literal, 641 exp.Neg, 642 exp.Paren, 643 ) 644 645 PARAMETERIZABLE_TEXT_TYPES = { 646 exp.DataType.Type.NVARCHAR, 647 exp.DataType.Type.VARCHAR, 648 exp.DataType.Type.CHAR, 649 exp.DataType.Type.NCHAR, 650 } 651 652 # Expressions that need to have all CTEs under them bubbled up to them 653 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 654 655 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 656 657 __slots__ = ( 658 "pretty", 659 "identify", 660 "normalize", 661 "pad", 662 "_indent", 663 "normalize_functions", 664 "unsupported_level", 665 "max_unsupported", 666 "leading_comma", 667 "max_text_width", 668 "comments", 669 "dialect", 670 "unsupported_messages", 671 "_escaped_quote_end", 672 "_escaped_identifier_end", 673 "_next_name", 674 "_identifier_start", 675 "_identifier_end", 676 "_quote_json_path_key_using_brackets", 677 ) 678 679 def __init__( 680 self, 681 pretty: t.Optional[bool] = None, 682 identify: str | bool = False, 683 normalize: bool = False, 684 pad: int = 2, 685 indent: int = 2, 686 normalize_functions: t.Optional[str | bool] = None, 687 unsupported_level: ErrorLevel = ErrorLevel.WARN, 688 max_unsupported: int = 3, 689 leading_comma: bool = False, 690 max_text_width: int = 80, 691 comments: bool = True, 692 dialect: DialectType = None, 693 ): 694 import sqlglot 695 from sqlglot.dialects import Dialect 696 697 self.pretty = pretty if pretty is not None else sqlglot.pretty 698 self.identify = identify 699 self.normalize = normalize 700 self.pad = pad 701 self._indent = indent 702 self.unsupported_level = unsupported_level 703 self.max_unsupported = max_unsupported 704 self.leading_comma = leading_comma 705 self.max_text_width = max_text_width 706 self.comments = comments 707 self.dialect = Dialect.get_or_raise(dialect) 708 709 # This is both a Dialect property and a Generator argument, so we prioritize the latter 710 self.normalize_functions = ( 711 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 712 ) 713 714 self.unsupported_messages: t.List[str] = [] 715 self._escaped_quote_end: str = ( 716 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 717 ) 718 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 719 720 self._next_name = name_sequence("_t") 721 722 self._identifier_start = self.dialect.IDENTIFIER_START 723 self._identifier_end = self.dialect.IDENTIFIER_END 724 725 self._quote_json_path_key_using_brackets = True 726 727 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 728 """ 729 Generates the SQL string corresponding to the given syntax tree. 730 731 Args: 732 expression: The syntax tree. 733 copy: Whether to copy the expression. The generator performs mutations so 734 it is safer to copy. 735 736 Returns: 737 The SQL string corresponding to `expression`. 738 """ 739 if copy: 740 expression = expression.copy() 741 742 expression = self.preprocess(expression) 743 744 self.unsupported_messages = [] 745 sql = self.sql(expression).strip() 746 747 if self.pretty: 748 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 749 750 if self.unsupported_level == ErrorLevel.IGNORE: 751 return sql 752 753 if self.unsupported_level == ErrorLevel.WARN: 754 for msg in self.unsupported_messages: 755 logger.warning(msg) 756 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 757 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 758 759 return sql 760 761 def preprocess(self, expression: exp.Expression) -> exp.Expression: 762 """Apply generic preprocessing transformations to a given expression.""" 763 expression = self._move_ctes_to_top_level(expression) 764 765 if self.ENSURE_BOOLS: 766 from sqlglot.transforms import ensure_bools 767 768 expression = ensure_bools(expression) 769 770 return expression 771 772 def _move_ctes_to_top_level(self, expression: E) -> E: 773 if ( 774 not expression.parent 775 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 776 and any(node.parent is not expression for node in expression.find_all(exp.With)) 777 ): 778 from sqlglot.transforms import move_ctes_to_top_level 779 780 expression = move_ctes_to_top_level(expression) 781 return expression 782 783 def unsupported(self, message: str) -> None: 784 if self.unsupported_level == ErrorLevel.IMMEDIATE: 785 raise UnsupportedError(message) 786 self.unsupported_messages.append(message) 787 788 def sep(self, sep: str = " ") -> str: 789 return f"{sep.strip()}\n" if self.pretty else sep 790 791 def seg(self, sql: str, sep: str = " ") -> str: 792 return f"{self.sep(sep)}{sql}" 793 794 def pad_comment(self, comment: str) -> str: 795 comment = " " + comment if comment[0].strip() else comment 796 comment = comment + " " if comment[-1].strip() else comment 797 return comment 798 799 def maybe_comment( 800 self, 801 sql: str, 802 expression: t.Optional[exp.Expression] = None, 803 comments: t.Optional[t.List[str]] = None, 804 separated: bool = False, 805 ) -> str: 806 comments = ( 807 ((expression and expression.comments) if comments is None else comments) # type: ignore 808 if self.comments 809 else None 810 ) 811 812 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 813 return sql 814 815 comments_sql = " ".join( 816 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 817 ) 818 819 if not comments_sql: 820 return sql 821 822 comments_sql = self._replace_line_breaks(comments_sql) 823 824 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 825 return ( 826 f"{self.sep()}{comments_sql}{sql}" 827 if not sql or sql[0].isspace() 828 else f"{comments_sql}{self.sep()}{sql}" 829 ) 830 831 return f"{sql} {comments_sql}" 832 833 def wrap(self, expression: exp.Expression | str) -> str: 834 this_sql = ( 835 self.sql(expression) 836 if isinstance(expression, exp.UNWRAPPED_QUERIES) 837 else self.sql(expression, "this") 838 ) 839 if not this_sql: 840 return "()" 841 842 this_sql = self.indent(this_sql, level=1, pad=0) 843 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 844 845 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 846 original = self.identify 847 self.identify = False 848 result = func(*args, **kwargs) 849 self.identify = original 850 return result 851 852 def normalize_func(self, name: str) -> str: 853 if self.normalize_functions == "upper" or self.normalize_functions is True: 854 return name.upper() 855 if self.normalize_functions == "lower": 856 return name.lower() 857 return name 858 859 def indent( 860 self, 861 sql: str, 862 level: int = 0, 863 pad: t.Optional[int] = None, 864 skip_first: bool = False, 865 skip_last: bool = False, 866 ) -> str: 867 if not self.pretty or not sql: 868 return sql 869 870 pad = self.pad if pad is None else pad 871 lines = sql.split("\n") 872 873 return "\n".join( 874 ( 875 line 876 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 877 else f"{' ' * (level * self._indent + pad)}{line}" 878 ) 879 for i, line in enumerate(lines) 880 ) 881 882 def sql( 883 self, 884 expression: t.Optional[str | exp.Expression], 885 key: t.Optional[str] = None, 886 comment: bool = True, 887 ) -> str: 888 if not expression: 889 return "" 890 891 if isinstance(expression, str): 892 return expression 893 894 if key: 895 value = expression.args.get(key) 896 if value: 897 return self.sql(value) 898 return "" 899 900 transform = self.TRANSFORMS.get(expression.__class__) 901 902 if callable(transform): 903 sql = transform(self, expression) 904 elif isinstance(expression, exp.Expression): 905 exp_handler_name = f"{expression.key}_sql" 906 907 if hasattr(self, exp_handler_name): 908 sql = getattr(self, exp_handler_name)(expression) 909 elif isinstance(expression, exp.Func): 910 sql = self.function_fallback_sql(expression) 911 elif isinstance(expression, exp.Property): 912 sql = self.property_sql(expression) 913 else: 914 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 915 else: 916 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 917 918 return self.maybe_comment(sql, expression) if self.comments and comment else sql 919 920 def uncache_sql(self, expression: exp.Uncache) -> str: 921 table = self.sql(expression, "this") 922 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 923 return f"UNCACHE TABLE{exists_sql} {table}" 924 925 def cache_sql(self, expression: exp.Cache) -> str: 926 lazy = " LAZY" if expression.args.get("lazy") else "" 927 table = self.sql(expression, "this") 928 options = expression.args.get("options") 929 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 930 sql = self.sql(expression, "expression") 931 sql = f" AS{self.sep()}{sql}" if sql else "" 932 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 933 return self.prepend_ctes(expression, sql) 934 935 def characterset_sql(self, expression: exp.CharacterSet) -> str: 936 if isinstance(expression.parent, exp.Cast): 937 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 938 default = "DEFAULT " if expression.args.get("default") else "" 939 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 940 941 def column_parts(self, expression: exp.Column) -> str: 942 return ".".join( 943 self.sql(part) 944 for part in ( 945 expression.args.get("catalog"), 946 expression.args.get("db"), 947 expression.args.get("table"), 948 expression.args.get("this"), 949 ) 950 if part 951 ) 952 953 def column_sql(self, expression: exp.Column) -> str: 954 join_mark = " (+)" if expression.args.get("join_mark") else "" 955 956 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 957 join_mark = "" 958 self.unsupported("Outer join syntax using the (+) operator is not supported.") 959 960 return f"{self.column_parts(expression)}{join_mark}" 961 962 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 963 this = self.sql(expression, "this") 964 this = f" {this}" if this else "" 965 position = self.sql(expression, "position") 966 return f"{position}{this}" 967 968 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 969 column = self.sql(expression, "this") 970 kind = self.sql(expression, "kind") 971 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 972 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 973 kind = f"{sep}{kind}" if kind else "" 974 constraints = f" {constraints}" if constraints else "" 975 position = self.sql(expression, "position") 976 position = f" {position}" if position else "" 977 978 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 979 kind = "" 980 981 return f"{exists}{column}{kind}{constraints}{position}" 982 983 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 984 this = self.sql(expression, "this") 985 kind_sql = self.sql(expression, "kind").strip() 986 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 987 988 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 989 this = self.sql(expression, "this") 990 if expression.args.get("not_null"): 991 persisted = " PERSISTED NOT NULL" 992 elif expression.args.get("persisted"): 993 persisted = " PERSISTED" 994 else: 995 persisted = "" 996 return f"AS {this}{persisted}" 997 998 def autoincrementcolumnconstraint_sql(self, _) -> str: 999 return self.token_sql(TokenType.AUTO_INCREMENT) 1000 1001 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1002 if isinstance(expression.this, list): 1003 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1004 else: 1005 this = self.sql(expression, "this") 1006 1007 return f"COMPRESS {this}" 1008 1009 def generatedasidentitycolumnconstraint_sql( 1010 self, expression: exp.GeneratedAsIdentityColumnConstraint 1011 ) -> str: 1012 this = "" 1013 if expression.this is not None: 1014 on_null = " ON NULL" if expression.args.get("on_null") else "" 1015 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1016 1017 start = expression.args.get("start") 1018 start = f"START WITH {start}" if start else "" 1019 increment = expression.args.get("increment") 1020 increment = f" INCREMENT BY {increment}" if increment else "" 1021 minvalue = expression.args.get("minvalue") 1022 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1023 maxvalue = expression.args.get("maxvalue") 1024 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1025 cycle = expression.args.get("cycle") 1026 cycle_sql = "" 1027 1028 if cycle is not None: 1029 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1030 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1031 1032 sequence_opts = "" 1033 if start or increment or cycle_sql: 1034 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1035 sequence_opts = f" ({sequence_opts.strip()})" 1036 1037 expr = self.sql(expression, "expression") 1038 expr = f"({expr})" if expr else "IDENTITY" 1039 1040 return f"GENERATED{this} AS {expr}{sequence_opts}" 1041 1042 def generatedasrowcolumnconstraint_sql( 1043 self, expression: exp.GeneratedAsRowColumnConstraint 1044 ) -> str: 1045 start = "START" if expression.args.get("start") else "END" 1046 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1047 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1048 1049 def periodforsystemtimeconstraint_sql( 1050 self, expression: exp.PeriodForSystemTimeConstraint 1051 ) -> str: 1052 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1053 1054 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1055 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1056 1057 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1058 return f"AS {self.sql(expression, 'this')}" 1059 1060 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1061 desc = expression.args.get("desc") 1062 if desc is not None: 1063 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1064 return "PRIMARY KEY" 1065 1066 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1067 this = self.sql(expression, "this") 1068 this = f" {this}" if this else "" 1069 index_type = expression.args.get("index_type") 1070 index_type = f" USING {index_type}" if index_type else "" 1071 on_conflict = self.sql(expression, "on_conflict") 1072 on_conflict = f" {on_conflict}" if on_conflict else "" 1073 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1074 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1075 1076 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1077 return self.sql(expression, "this") 1078 1079 def create_sql(self, expression: exp.Create) -> str: 1080 kind = self.sql(expression, "kind") 1081 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1082 properties = expression.args.get("properties") 1083 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1084 1085 this = self.createable_sql(expression, properties_locs) 1086 1087 properties_sql = "" 1088 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1089 exp.Properties.Location.POST_WITH 1090 ): 1091 properties_sql = self.sql( 1092 exp.Properties( 1093 expressions=[ 1094 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1095 *properties_locs[exp.Properties.Location.POST_WITH], 1096 ] 1097 ) 1098 ) 1099 1100 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1101 properties_sql = self.sep() + properties_sql 1102 elif not self.pretty: 1103 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1104 properties_sql = f" {properties_sql}" 1105 1106 begin = " BEGIN" if expression.args.get("begin") else "" 1107 end = " END" if expression.args.get("end") else "" 1108 1109 expression_sql = self.sql(expression, "expression") 1110 if expression_sql: 1111 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1112 1113 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1114 postalias_props_sql = "" 1115 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1116 postalias_props_sql = self.properties( 1117 exp.Properties( 1118 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1119 ), 1120 wrapped=False, 1121 ) 1122 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1123 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1124 1125 postindex_props_sql = "" 1126 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1127 postindex_props_sql = self.properties( 1128 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1129 wrapped=False, 1130 prefix=" ", 1131 ) 1132 1133 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1134 indexes = f" {indexes}" if indexes else "" 1135 index_sql = indexes + postindex_props_sql 1136 1137 replace = " OR REPLACE" if expression.args.get("replace") else "" 1138 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1139 unique = " UNIQUE" if expression.args.get("unique") else "" 1140 1141 clustered = expression.args.get("clustered") 1142 if clustered is None: 1143 clustered_sql = "" 1144 elif clustered: 1145 clustered_sql = " CLUSTERED COLUMNSTORE" 1146 else: 1147 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1148 1149 postcreate_props_sql = "" 1150 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1151 postcreate_props_sql = self.properties( 1152 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1153 sep=" ", 1154 prefix=" ", 1155 wrapped=False, 1156 ) 1157 1158 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1159 1160 postexpression_props_sql = "" 1161 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1162 postexpression_props_sql = self.properties( 1163 exp.Properties( 1164 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1165 ), 1166 sep=" ", 1167 prefix=" ", 1168 wrapped=False, 1169 ) 1170 1171 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1172 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1173 no_schema_binding = ( 1174 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1175 ) 1176 1177 clone = self.sql(expression, "clone") 1178 clone = f" {clone}" if clone else "" 1179 1180 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1181 properties_expression = f"{expression_sql}{properties_sql}" 1182 else: 1183 properties_expression = f"{properties_sql}{expression_sql}" 1184 1185 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1186 return self.prepend_ctes(expression, expression_sql) 1187 1188 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1189 start = self.sql(expression, "start") 1190 start = f"START WITH {start}" if start else "" 1191 increment = self.sql(expression, "increment") 1192 increment = f" INCREMENT BY {increment}" if increment else "" 1193 minvalue = self.sql(expression, "minvalue") 1194 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1195 maxvalue = self.sql(expression, "maxvalue") 1196 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1197 owned = self.sql(expression, "owned") 1198 owned = f" OWNED BY {owned}" if owned else "" 1199 1200 cache = expression.args.get("cache") 1201 if cache is None: 1202 cache_str = "" 1203 elif cache is True: 1204 cache_str = " CACHE" 1205 else: 1206 cache_str = f" CACHE {cache}" 1207 1208 options = self.expressions(expression, key="options", flat=True, sep=" ") 1209 options = f" {options}" if options else "" 1210 1211 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1212 1213 def clone_sql(self, expression: exp.Clone) -> str: 1214 this = self.sql(expression, "this") 1215 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1216 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1217 return f"{shallow}{keyword} {this}" 1218 1219 def describe_sql(self, expression: exp.Describe) -> str: 1220 style = expression.args.get("style") 1221 style = f" {style}" if style else "" 1222 partition = self.sql(expression, "partition") 1223 partition = f" {partition}" if partition else "" 1224 format = self.sql(expression, "format") 1225 format = f" {format}" if format else "" 1226 1227 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1228 1229 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1230 tag = self.sql(expression, "tag") 1231 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1232 1233 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1234 with_ = self.sql(expression, "with") 1235 if with_: 1236 sql = f"{with_}{self.sep()}{sql}" 1237 return sql 1238 1239 def with_sql(self, expression: exp.With) -> str: 1240 sql = self.expressions(expression, flat=True) 1241 recursive = ( 1242 "RECURSIVE " 1243 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1244 else "" 1245 ) 1246 search = self.sql(expression, "search") 1247 search = f" {search}" if search else "" 1248 1249 return f"WITH {recursive}{sql}{search}" 1250 1251 def cte_sql(self, expression: exp.CTE) -> str: 1252 alias = expression.args.get("alias") 1253 if alias: 1254 alias.add_comments(expression.pop_comments()) 1255 1256 alias_sql = self.sql(expression, "alias") 1257 1258 materialized = expression.args.get("materialized") 1259 if materialized is False: 1260 materialized = "NOT MATERIALIZED " 1261 elif materialized: 1262 materialized = "MATERIALIZED " 1263 1264 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1265 1266 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1267 alias = self.sql(expression, "this") 1268 columns = self.expressions(expression, key="columns", flat=True) 1269 columns = f"({columns})" if columns else "" 1270 1271 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1272 columns = "" 1273 self.unsupported("Named columns are not supported in table alias.") 1274 1275 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1276 alias = self._next_name() 1277 1278 return f"{alias}{columns}" 1279 1280 def bitstring_sql(self, expression: exp.BitString) -> str: 1281 this = self.sql(expression, "this") 1282 if self.dialect.BIT_START: 1283 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1284 return f"{int(this, 2)}" 1285 1286 def hexstring_sql( 1287 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1288 ) -> str: 1289 this = self.sql(expression, "this") 1290 is_integer_type = expression.args.get("is_integer") 1291 1292 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1293 not self.dialect.HEX_START and not binary_function_repr 1294 ): 1295 # Integer representation will be returned if: 1296 # - The read dialect treats the hex value as integer literal but not the write 1297 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1298 return f"{int(this, 16)}" 1299 1300 if not is_integer_type: 1301 # Read dialect treats the hex value as BINARY/BLOB 1302 if binary_function_repr: 1303 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1304 return self.func(binary_function_repr, exp.Literal.string(this)) 1305 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1306 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1307 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1308 1309 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1310 1311 def bytestring_sql(self, expression: exp.ByteString) -> str: 1312 this = self.sql(expression, "this") 1313 if self.dialect.BYTE_START: 1314 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1315 return this 1316 1317 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1318 this = self.sql(expression, "this") 1319 escape = expression.args.get("escape") 1320 1321 if self.dialect.UNICODE_START: 1322 escape_substitute = r"\\\1" 1323 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1324 else: 1325 escape_substitute = r"\\u\1" 1326 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1327 1328 if escape: 1329 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1330 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1331 else: 1332 escape_pattern = ESCAPED_UNICODE_RE 1333 escape_sql = "" 1334 1335 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1336 this = escape_pattern.sub(escape_substitute, this) 1337 1338 return f"{left_quote}{this}{right_quote}{escape_sql}" 1339 1340 def rawstring_sql(self, expression: exp.RawString) -> str: 1341 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1342 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1343 1344 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1345 this = self.sql(expression, "this") 1346 specifier = self.sql(expression, "expression") 1347 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1348 return f"{this}{specifier}" 1349 1350 def datatype_sql(self, expression: exp.DataType) -> str: 1351 nested = "" 1352 values = "" 1353 interior = self.expressions(expression, flat=True) 1354 1355 type_value = expression.this 1356 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1357 type_sql = self.sql(expression, "kind") 1358 else: 1359 type_sql = ( 1360 self.TYPE_MAPPING.get(type_value, type_value.value) 1361 if isinstance(type_value, exp.DataType.Type) 1362 else type_value 1363 ) 1364 1365 if interior: 1366 if expression.args.get("nested"): 1367 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1368 if expression.args.get("values") is not None: 1369 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1370 values = self.expressions(expression, key="values", flat=True) 1371 values = f"{delimiters[0]}{values}{delimiters[1]}" 1372 elif type_value == exp.DataType.Type.INTERVAL: 1373 nested = f" {interior}" 1374 else: 1375 nested = f"({interior})" 1376 1377 type_sql = f"{type_sql}{nested}{values}" 1378 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1379 exp.DataType.Type.TIMETZ, 1380 exp.DataType.Type.TIMESTAMPTZ, 1381 ): 1382 type_sql = f"{type_sql} WITH TIME ZONE" 1383 1384 return type_sql 1385 1386 def directory_sql(self, expression: exp.Directory) -> str: 1387 local = "LOCAL " if expression.args.get("local") else "" 1388 row_format = self.sql(expression, "row_format") 1389 row_format = f" {row_format}" if row_format else "" 1390 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1391 1392 def delete_sql(self, expression: exp.Delete) -> str: 1393 this = self.sql(expression, "this") 1394 this = f" FROM {this}" if this else "" 1395 using = self.sql(expression, "using") 1396 using = f" USING {using}" if using else "" 1397 cluster = self.sql(expression, "cluster") 1398 cluster = f" {cluster}" if cluster else "" 1399 where = self.sql(expression, "where") 1400 returning = self.sql(expression, "returning") 1401 limit = self.sql(expression, "limit") 1402 tables = self.expressions(expression, key="tables") 1403 tables = f" {tables}" if tables else "" 1404 if self.RETURNING_END: 1405 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1406 else: 1407 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1408 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1409 1410 def drop_sql(self, expression: exp.Drop) -> str: 1411 this = self.sql(expression, "this") 1412 expressions = self.expressions(expression, flat=True) 1413 expressions = f" ({expressions})" if expressions else "" 1414 kind = expression.args["kind"] 1415 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1416 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1417 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1418 on_cluster = self.sql(expression, "cluster") 1419 on_cluster = f" {on_cluster}" if on_cluster else "" 1420 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1421 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1422 cascade = " CASCADE" if expression.args.get("cascade") else "" 1423 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1424 purge = " PURGE" if expression.args.get("purge") else "" 1425 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1426 1427 def set_operation(self, expression: exp.SetOperation) -> str: 1428 op_type = type(expression) 1429 op_name = op_type.key.upper() 1430 1431 distinct = expression.args.get("distinct") 1432 if ( 1433 distinct is False 1434 and op_type in (exp.Except, exp.Intersect) 1435 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1436 ): 1437 self.unsupported(f"{op_name} ALL is not supported") 1438 1439 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1440 1441 if distinct is None: 1442 distinct = default_distinct 1443 if distinct is None: 1444 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1445 1446 if distinct is default_distinct: 1447 kind = "" 1448 else: 1449 kind = " DISTINCT" if distinct else " ALL" 1450 1451 by_name = " BY NAME" if expression.args.get("by_name") else "" 1452 return f"{op_name}{kind}{by_name}" 1453 1454 def set_operations(self, expression: exp.SetOperation) -> str: 1455 if not self.SET_OP_MODIFIERS: 1456 limit = expression.args.get("limit") 1457 order = expression.args.get("order") 1458 1459 if limit or order: 1460 select = self._move_ctes_to_top_level( 1461 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1462 ) 1463 1464 if limit: 1465 select = select.limit(limit.pop(), copy=False) 1466 if order: 1467 select = select.order_by(order.pop(), copy=False) 1468 return self.sql(select) 1469 1470 sqls: t.List[str] = [] 1471 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1472 1473 while stack: 1474 node = stack.pop() 1475 1476 if isinstance(node, exp.SetOperation): 1477 stack.append(node.expression) 1478 stack.append( 1479 self.maybe_comment( 1480 self.set_operation(node), comments=node.comments, separated=True 1481 ) 1482 ) 1483 stack.append(node.this) 1484 else: 1485 sqls.append(self.sql(node)) 1486 1487 this = self.sep().join(sqls) 1488 this = self.query_modifiers(expression, this) 1489 return self.prepend_ctes(expression, this) 1490 1491 def fetch_sql(self, expression: exp.Fetch) -> str: 1492 direction = expression.args.get("direction") 1493 direction = f" {direction}" if direction else "" 1494 count = self.sql(expression, "count") 1495 count = f" {count}" if count else "" 1496 limit_options = self.sql(expression, "limit_options") 1497 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1498 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1499 1500 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1501 percent = " PERCENT" if expression.args.get("percent") else "" 1502 rows = " ROWS" if expression.args.get("rows") else "" 1503 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1504 if not with_ties and rows: 1505 with_ties = " ONLY" 1506 return f"{percent}{rows}{with_ties}" 1507 1508 def filter_sql(self, expression: exp.Filter) -> str: 1509 if self.AGGREGATE_FILTER_SUPPORTED: 1510 this = self.sql(expression, "this") 1511 where = self.sql(expression, "expression").strip() 1512 return f"{this} FILTER({where})" 1513 1514 agg = expression.this 1515 agg_arg = agg.this 1516 cond = expression.expression.this 1517 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1518 return self.sql(agg) 1519 1520 def hint_sql(self, expression: exp.Hint) -> str: 1521 if not self.QUERY_HINTS: 1522 self.unsupported("Hints are not supported") 1523 return "" 1524 1525 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1526 1527 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1528 using = self.sql(expression, "using") 1529 using = f" USING {using}" if using else "" 1530 columns = self.expressions(expression, key="columns", flat=True) 1531 columns = f"({columns})" if columns else "" 1532 partition_by = self.expressions(expression, key="partition_by", flat=True) 1533 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1534 where = self.sql(expression, "where") 1535 include = self.expressions(expression, key="include", flat=True) 1536 if include: 1537 include = f" INCLUDE ({include})" 1538 with_storage = self.expressions(expression, key="with_storage", flat=True) 1539 with_storage = f" WITH ({with_storage})" if with_storage else "" 1540 tablespace = self.sql(expression, "tablespace") 1541 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1542 on = self.sql(expression, "on") 1543 on = f" ON {on}" if on else "" 1544 1545 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1546 1547 def index_sql(self, expression: exp.Index) -> str: 1548 unique = "UNIQUE " if expression.args.get("unique") else "" 1549 primary = "PRIMARY " if expression.args.get("primary") else "" 1550 amp = "AMP " if expression.args.get("amp") else "" 1551 name = self.sql(expression, "this") 1552 name = f"{name} " if name else "" 1553 table = self.sql(expression, "table") 1554 table = f"{self.INDEX_ON} {table}" if table else "" 1555 1556 index = "INDEX " if not table else "" 1557 1558 params = self.sql(expression, "params") 1559 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1560 1561 def identifier_sql(self, expression: exp.Identifier) -> str: 1562 text = expression.name 1563 lower = text.lower() 1564 text = lower if self.normalize and not expression.quoted else text 1565 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1566 if ( 1567 expression.quoted 1568 or self.dialect.can_identify(text, self.identify) 1569 or lower in self.RESERVED_KEYWORDS 1570 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1571 ): 1572 text = f"{self._identifier_start}{text}{self._identifier_end}" 1573 return text 1574 1575 def hex_sql(self, expression: exp.Hex) -> str: 1576 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1577 if self.dialect.HEX_LOWERCASE: 1578 text = self.func("LOWER", text) 1579 1580 return text 1581 1582 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1583 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1584 if not self.dialect.HEX_LOWERCASE: 1585 text = self.func("LOWER", text) 1586 return text 1587 1588 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1589 input_format = self.sql(expression, "input_format") 1590 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1591 output_format = self.sql(expression, "output_format") 1592 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1593 return self.sep().join((input_format, output_format)) 1594 1595 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1596 string = self.sql(exp.Literal.string(expression.name)) 1597 return f"{prefix}{string}" 1598 1599 def partition_sql(self, expression: exp.Partition) -> str: 1600 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1601 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1602 1603 def properties_sql(self, expression: exp.Properties) -> str: 1604 root_properties = [] 1605 with_properties = [] 1606 1607 for p in expression.expressions: 1608 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1609 if p_loc == exp.Properties.Location.POST_WITH: 1610 with_properties.append(p) 1611 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1612 root_properties.append(p) 1613 1614 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1615 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1616 1617 if root_props and with_props and not self.pretty: 1618 with_props = " " + with_props 1619 1620 return root_props + with_props 1621 1622 def root_properties(self, properties: exp.Properties) -> str: 1623 if properties.expressions: 1624 return self.expressions(properties, indent=False, sep=" ") 1625 return "" 1626 1627 def properties( 1628 self, 1629 properties: exp.Properties, 1630 prefix: str = "", 1631 sep: str = ", ", 1632 suffix: str = "", 1633 wrapped: bool = True, 1634 ) -> str: 1635 if properties.expressions: 1636 expressions = self.expressions(properties, sep=sep, indent=False) 1637 if expressions: 1638 expressions = self.wrap(expressions) if wrapped else expressions 1639 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1640 return "" 1641 1642 def with_properties(self, properties: exp.Properties) -> str: 1643 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1644 1645 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1646 properties_locs = defaultdict(list) 1647 for p in properties.expressions: 1648 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1649 if p_loc != exp.Properties.Location.UNSUPPORTED: 1650 properties_locs[p_loc].append(p) 1651 else: 1652 self.unsupported(f"Unsupported property {p.key}") 1653 1654 return properties_locs 1655 1656 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1657 if isinstance(expression.this, exp.Dot): 1658 return self.sql(expression, "this") 1659 return f"'{expression.name}'" if string_key else expression.name 1660 1661 def property_sql(self, expression: exp.Property) -> str: 1662 property_cls = expression.__class__ 1663 if property_cls == exp.Property: 1664 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1665 1666 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1667 if not property_name: 1668 self.unsupported(f"Unsupported property {expression.key}") 1669 1670 return f"{property_name}={self.sql(expression, 'this')}" 1671 1672 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1673 if self.SUPPORTS_CREATE_TABLE_LIKE: 1674 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1675 options = f" {options}" if options else "" 1676 1677 like = f"LIKE {self.sql(expression, 'this')}{options}" 1678 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1679 like = f"({like})" 1680 1681 return like 1682 1683 if expression.expressions: 1684 self.unsupported("Transpilation of LIKE property options is unsupported") 1685 1686 select = exp.select("*").from_(expression.this).limit(0) 1687 return f"AS {self.sql(select)}" 1688 1689 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1690 no = "NO " if expression.args.get("no") else "" 1691 protection = " PROTECTION" if expression.args.get("protection") else "" 1692 return f"{no}FALLBACK{protection}" 1693 1694 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1695 no = "NO " if expression.args.get("no") else "" 1696 local = expression.args.get("local") 1697 local = f"{local} " if local else "" 1698 dual = "DUAL " if expression.args.get("dual") else "" 1699 before = "BEFORE " if expression.args.get("before") else "" 1700 after = "AFTER " if expression.args.get("after") else "" 1701 return f"{no}{local}{dual}{before}{after}JOURNAL" 1702 1703 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1704 freespace = self.sql(expression, "this") 1705 percent = " PERCENT" if expression.args.get("percent") else "" 1706 return f"FREESPACE={freespace}{percent}" 1707 1708 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1709 if expression.args.get("default"): 1710 property = "DEFAULT" 1711 elif expression.args.get("on"): 1712 property = "ON" 1713 else: 1714 property = "OFF" 1715 return f"CHECKSUM={property}" 1716 1717 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1718 if expression.args.get("no"): 1719 return "NO MERGEBLOCKRATIO" 1720 if expression.args.get("default"): 1721 return "DEFAULT MERGEBLOCKRATIO" 1722 1723 percent = " PERCENT" if expression.args.get("percent") else "" 1724 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1725 1726 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1727 default = expression.args.get("default") 1728 minimum = expression.args.get("minimum") 1729 maximum = expression.args.get("maximum") 1730 if default or minimum or maximum: 1731 if default: 1732 prop = "DEFAULT" 1733 elif minimum: 1734 prop = "MINIMUM" 1735 else: 1736 prop = "MAXIMUM" 1737 return f"{prop} DATABLOCKSIZE" 1738 units = expression.args.get("units") 1739 units = f" {units}" if units else "" 1740 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1741 1742 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1743 autotemp = expression.args.get("autotemp") 1744 always = expression.args.get("always") 1745 default = expression.args.get("default") 1746 manual = expression.args.get("manual") 1747 never = expression.args.get("never") 1748 1749 if autotemp is not None: 1750 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1751 elif always: 1752 prop = "ALWAYS" 1753 elif default: 1754 prop = "DEFAULT" 1755 elif manual: 1756 prop = "MANUAL" 1757 elif never: 1758 prop = "NEVER" 1759 return f"BLOCKCOMPRESSION={prop}" 1760 1761 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1762 no = expression.args.get("no") 1763 no = " NO" if no else "" 1764 concurrent = expression.args.get("concurrent") 1765 concurrent = " CONCURRENT" if concurrent else "" 1766 target = self.sql(expression, "target") 1767 target = f" {target}" if target else "" 1768 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1769 1770 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1771 if isinstance(expression.this, list): 1772 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1773 if expression.this: 1774 modulus = self.sql(expression, "this") 1775 remainder = self.sql(expression, "expression") 1776 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1777 1778 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1779 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1780 return f"FROM ({from_expressions}) TO ({to_expressions})" 1781 1782 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1783 this = self.sql(expression, "this") 1784 1785 for_values_or_default = expression.expression 1786 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1787 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1788 else: 1789 for_values_or_default = " DEFAULT" 1790 1791 return f"PARTITION OF {this}{for_values_or_default}" 1792 1793 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1794 kind = expression.args.get("kind") 1795 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1796 for_or_in = expression.args.get("for_or_in") 1797 for_or_in = f" {for_or_in}" if for_or_in else "" 1798 lock_type = expression.args.get("lock_type") 1799 override = " OVERRIDE" if expression.args.get("override") else "" 1800 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1801 1802 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1803 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1804 statistics = expression.args.get("statistics") 1805 statistics_sql = "" 1806 if statistics is not None: 1807 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1808 return f"{data_sql}{statistics_sql}" 1809 1810 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1811 this = self.sql(expression, "this") 1812 this = f"HISTORY_TABLE={this}" if this else "" 1813 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1814 data_consistency = ( 1815 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1816 ) 1817 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1818 retention_period = ( 1819 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1820 ) 1821 1822 if this: 1823 on_sql = self.func("ON", this, data_consistency, retention_period) 1824 else: 1825 on_sql = "ON" if expression.args.get("on") else "OFF" 1826 1827 sql = f"SYSTEM_VERSIONING={on_sql}" 1828 1829 return f"WITH({sql})" if expression.args.get("with") else sql 1830 1831 def insert_sql(self, expression: exp.Insert) -> str: 1832 hint = self.sql(expression, "hint") 1833 overwrite = expression.args.get("overwrite") 1834 1835 if isinstance(expression.this, exp.Directory): 1836 this = " OVERWRITE" if overwrite else " INTO" 1837 else: 1838 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1839 1840 stored = self.sql(expression, "stored") 1841 stored = f" {stored}" if stored else "" 1842 alternative = expression.args.get("alternative") 1843 alternative = f" OR {alternative}" if alternative else "" 1844 ignore = " IGNORE" if expression.args.get("ignore") else "" 1845 is_function = expression.args.get("is_function") 1846 if is_function: 1847 this = f"{this} FUNCTION" 1848 this = f"{this} {self.sql(expression, 'this')}" 1849 1850 exists = " IF EXISTS" if expression.args.get("exists") else "" 1851 where = self.sql(expression, "where") 1852 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1853 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1854 on_conflict = self.sql(expression, "conflict") 1855 on_conflict = f" {on_conflict}" if on_conflict else "" 1856 by_name = " BY NAME" if expression.args.get("by_name") else "" 1857 returning = self.sql(expression, "returning") 1858 1859 if self.RETURNING_END: 1860 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1861 else: 1862 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1863 1864 partition_by = self.sql(expression, "partition") 1865 partition_by = f" {partition_by}" if partition_by else "" 1866 settings = self.sql(expression, "settings") 1867 settings = f" {settings}" if settings else "" 1868 1869 source = self.sql(expression, "source") 1870 source = f"TABLE {source}" if source else "" 1871 1872 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1873 return self.prepend_ctes(expression, sql) 1874 1875 def introducer_sql(self, expression: exp.Introducer) -> str: 1876 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1877 1878 def kill_sql(self, expression: exp.Kill) -> str: 1879 kind = self.sql(expression, "kind") 1880 kind = f" {kind}" if kind else "" 1881 this = self.sql(expression, "this") 1882 this = f" {this}" if this else "" 1883 return f"KILL{kind}{this}" 1884 1885 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1886 return expression.name 1887 1888 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1889 return expression.name 1890 1891 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1892 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1893 1894 constraint = self.sql(expression, "constraint") 1895 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1896 1897 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1898 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1899 action = self.sql(expression, "action") 1900 1901 expressions = self.expressions(expression, flat=True) 1902 if expressions: 1903 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1904 expressions = f" {set_keyword}{expressions}" 1905 1906 where = self.sql(expression, "where") 1907 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1908 1909 def returning_sql(self, expression: exp.Returning) -> str: 1910 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1911 1912 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1913 fields = self.sql(expression, "fields") 1914 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1915 escaped = self.sql(expression, "escaped") 1916 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1917 items = self.sql(expression, "collection_items") 1918 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1919 keys = self.sql(expression, "map_keys") 1920 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1921 lines = self.sql(expression, "lines") 1922 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1923 null = self.sql(expression, "null") 1924 null = f" NULL DEFINED AS {null}" if null else "" 1925 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1926 1927 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1928 return f"WITH ({self.expressions(expression, flat=True)})" 1929 1930 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1931 this = f"{self.sql(expression, 'this')} INDEX" 1932 target = self.sql(expression, "target") 1933 target = f" FOR {target}" if target else "" 1934 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1935 1936 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1937 this = self.sql(expression, "this") 1938 kind = self.sql(expression, "kind") 1939 expr = self.sql(expression, "expression") 1940 return f"{this} ({kind} => {expr})" 1941 1942 def table_parts(self, expression: exp.Table) -> str: 1943 return ".".join( 1944 self.sql(part) 1945 for part in ( 1946 expression.args.get("catalog"), 1947 expression.args.get("db"), 1948 expression.args.get("this"), 1949 ) 1950 if part is not None 1951 ) 1952 1953 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1954 table = self.table_parts(expression) 1955 only = "ONLY " if expression.args.get("only") else "" 1956 partition = self.sql(expression, "partition") 1957 partition = f" {partition}" if partition else "" 1958 version = self.sql(expression, "version") 1959 version = f" {version}" if version else "" 1960 alias = self.sql(expression, "alias") 1961 alias = f"{sep}{alias}" if alias else "" 1962 1963 sample = self.sql(expression, "sample") 1964 if self.dialect.ALIAS_POST_TABLESAMPLE: 1965 sample_pre_alias = sample 1966 sample_post_alias = "" 1967 else: 1968 sample_pre_alias = "" 1969 sample_post_alias = sample 1970 1971 hints = self.expressions(expression, key="hints", sep=" ") 1972 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1973 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1974 joins = self.indent( 1975 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1976 ) 1977 laterals = self.expressions(expression, key="laterals", sep="") 1978 1979 file_format = self.sql(expression, "format") 1980 if file_format: 1981 pattern = self.sql(expression, "pattern") 1982 pattern = f", PATTERN => {pattern}" if pattern else "" 1983 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1984 1985 ordinality = expression.args.get("ordinality") or "" 1986 if ordinality: 1987 ordinality = f" WITH ORDINALITY{alias}" 1988 alias = "" 1989 1990 when = self.sql(expression, "when") 1991 if when: 1992 table = f"{table} {when}" 1993 1994 changes = self.sql(expression, "changes") 1995 changes = f" {changes}" if changes else "" 1996 1997 rows_from = self.expressions(expression, key="rows_from") 1998 if rows_from: 1999 table = f"ROWS FROM {self.wrap(rows_from)}" 2000 2001 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2002 2003 def tablesample_sql( 2004 self, 2005 expression: exp.TableSample, 2006 tablesample_keyword: t.Optional[str] = None, 2007 ) -> str: 2008 method = self.sql(expression, "method") 2009 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2010 numerator = self.sql(expression, "bucket_numerator") 2011 denominator = self.sql(expression, "bucket_denominator") 2012 field = self.sql(expression, "bucket_field") 2013 field = f" ON {field}" if field else "" 2014 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2015 seed = self.sql(expression, "seed") 2016 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2017 2018 size = self.sql(expression, "size") 2019 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2020 size = f"{size} ROWS" 2021 2022 percent = self.sql(expression, "percent") 2023 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2024 percent = f"{percent} PERCENT" 2025 2026 expr = f"{bucket}{percent}{size}" 2027 if self.TABLESAMPLE_REQUIRES_PARENS: 2028 expr = f"({expr})" 2029 2030 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2031 2032 def pivot_sql(self, expression: exp.Pivot) -> str: 2033 expressions = self.expressions(expression, flat=True) 2034 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2035 2036 if expression.this: 2037 this = self.sql(expression, "this") 2038 if not expressions: 2039 return f"UNPIVOT {this}" 2040 2041 on = f"{self.seg('ON')} {expressions}" 2042 into = self.sql(expression, "into") 2043 into = f"{self.seg('INTO')} {into}" if into else "" 2044 using = self.expressions(expression, key="using", flat=True) 2045 using = f"{self.seg('USING')} {using}" if using else "" 2046 group = self.sql(expression, "group") 2047 return f"{direction} {this}{on}{into}{using}{group}" 2048 2049 alias = self.sql(expression, "alias") 2050 alias = f" AS {alias}" if alias else "" 2051 2052 field = self.sql(expression, "field") 2053 2054 include_nulls = expression.args.get("include_nulls") 2055 if include_nulls is not None: 2056 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2057 else: 2058 nulls = "" 2059 2060 default_on_null = self.sql(expression, "default_on_null") 2061 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2062 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2063 2064 def version_sql(self, expression: exp.Version) -> str: 2065 this = f"FOR {expression.name}" 2066 kind = expression.text("kind") 2067 expr = self.sql(expression, "expression") 2068 return f"{this} {kind} {expr}" 2069 2070 def tuple_sql(self, expression: exp.Tuple) -> str: 2071 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2072 2073 def update_sql(self, expression: exp.Update) -> str: 2074 this = self.sql(expression, "this") 2075 set_sql = self.expressions(expression, flat=True) 2076 from_sql = self.sql(expression, "from") 2077 where_sql = self.sql(expression, "where") 2078 returning = self.sql(expression, "returning") 2079 order = self.sql(expression, "order") 2080 limit = self.sql(expression, "limit") 2081 if self.RETURNING_END: 2082 expression_sql = f"{from_sql}{where_sql}{returning}" 2083 else: 2084 expression_sql = f"{returning}{from_sql}{where_sql}" 2085 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2086 return self.prepend_ctes(expression, sql) 2087 2088 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2089 values_as_table = values_as_table and self.VALUES_AS_TABLE 2090 2091 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2092 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2093 args = self.expressions(expression) 2094 alias = self.sql(expression, "alias") 2095 values = f"VALUES{self.seg('')}{args}" 2096 values = ( 2097 f"({values})" 2098 if self.WRAP_DERIVED_VALUES 2099 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2100 else values 2101 ) 2102 return f"{values} AS {alias}" if alias else values 2103 2104 # Converts `VALUES...` expression into a series of select unions. 2105 alias_node = expression.args.get("alias") 2106 column_names = alias_node and alias_node.columns 2107 2108 selects: t.List[exp.Query] = [] 2109 2110 for i, tup in enumerate(expression.expressions): 2111 row = tup.expressions 2112 2113 if i == 0 and column_names: 2114 row = [ 2115 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2116 ] 2117 2118 selects.append(exp.Select(expressions=row)) 2119 2120 if self.pretty: 2121 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2122 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2123 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2124 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2125 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2126 2127 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2128 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2129 return f"({unions}){alias}" 2130 2131 def var_sql(self, expression: exp.Var) -> str: 2132 return self.sql(expression, "this") 2133 2134 @unsupported_args("expressions") 2135 def into_sql(self, expression: exp.Into) -> str: 2136 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2137 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2138 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2139 2140 def from_sql(self, expression: exp.From) -> str: 2141 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2142 2143 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2144 grouping_sets = self.expressions(expression, indent=False) 2145 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2146 2147 def rollup_sql(self, expression: exp.Rollup) -> str: 2148 expressions = self.expressions(expression, indent=False) 2149 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2150 2151 def cube_sql(self, expression: exp.Cube) -> str: 2152 expressions = self.expressions(expression, indent=False) 2153 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2154 2155 def group_sql(self, expression: exp.Group) -> str: 2156 group_by_all = expression.args.get("all") 2157 if group_by_all is True: 2158 modifier = " ALL" 2159 elif group_by_all is False: 2160 modifier = " DISTINCT" 2161 else: 2162 modifier = "" 2163 2164 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2165 2166 grouping_sets = self.expressions(expression, key="grouping_sets") 2167 cube = self.expressions(expression, key="cube") 2168 rollup = self.expressions(expression, key="rollup") 2169 2170 groupings = csv( 2171 self.seg(grouping_sets) if grouping_sets else "", 2172 self.seg(cube) if cube else "", 2173 self.seg(rollup) if rollup else "", 2174 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2175 sep=self.GROUPINGS_SEP, 2176 ) 2177 2178 if ( 2179 expression.expressions 2180 and groupings 2181 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2182 ): 2183 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2184 2185 return f"{group_by}{groupings}" 2186 2187 def having_sql(self, expression: exp.Having) -> str: 2188 this = self.indent(self.sql(expression, "this")) 2189 return f"{self.seg('HAVING')}{self.sep()}{this}" 2190 2191 def connect_sql(self, expression: exp.Connect) -> str: 2192 start = self.sql(expression, "start") 2193 start = self.seg(f"START WITH {start}") if start else "" 2194 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2195 connect = self.sql(expression, "connect") 2196 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2197 return start + connect 2198 2199 def prior_sql(self, expression: exp.Prior) -> str: 2200 return f"PRIOR {self.sql(expression, 'this')}" 2201 2202 def join_sql(self, expression: exp.Join) -> str: 2203 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2204 side = None 2205 else: 2206 side = expression.side 2207 2208 op_sql = " ".join( 2209 op 2210 for op in ( 2211 expression.method, 2212 "GLOBAL" if expression.args.get("global") else None, 2213 side, 2214 expression.kind, 2215 expression.hint if self.JOIN_HINTS else None, 2216 ) 2217 if op 2218 ) 2219 match_cond = self.sql(expression, "match_condition") 2220 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2221 on_sql = self.sql(expression, "on") 2222 using = expression.args.get("using") 2223 2224 if not on_sql and using: 2225 on_sql = csv(*(self.sql(column) for column in using)) 2226 2227 this = expression.this 2228 this_sql = self.sql(this) 2229 2230 exprs = self.expressions(expression) 2231 if exprs: 2232 this_sql = f"{this_sql},{self.seg(exprs)}" 2233 2234 if on_sql: 2235 on_sql = self.indent(on_sql, skip_first=True) 2236 space = self.seg(" " * self.pad) if self.pretty else " " 2237 if using: 2238 on_sql = f"{space}USING ({on_sql})" 2239 else: 2240 on_sql = f"{space}ON {on_sql}" 2241 elif not op_sql: 2242 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2243 return f" {this_sql}" 2244 2245 return f", {this_sql}" 2246 2247 if op_sql != "STRAIGHT_JOIN": 2248 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2249 2250 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2251 2252 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2253 args = self.expressions(expression, flat=True) 2254 args = f"({args})" if len(args.split(",")) > 1 else args 2255 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2256 2257 def lateral_op(self, expression: exp.Lateral) -> str: 2258 cross_apply = expression.args.get("cross_apply") 2259 2260 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2261 if cross_apply is True: 2262 op = "INNER JOIN " 2263 elif cross_apply is False: 2264 op = "LEFT JOIN " 2265 else: 2266 op = "" 2267 2268 return f"{op}LATERAL" 2269 2270 def lateral_sql(self, expression: exp.Lateral) -> str: 2271 this = self.sql(expression, "this") 2272 2273 if expression.args.get("view"): 2274 alias = expression.args["alias"] 2275 columns = self.expressions(alias, key="columns", flat=True) 2276 table = f" {alias.name}" if alias.name else "" 2277 columns = f" AS {columns}" if columns else "" 2278 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2279 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2280 2281 alias = self.sql(expression, "alias") 2282 alias = f" AS {alias}" if alias else "" 2283 return f"{self.lateral_op(expression)} {this}{alias}" 2284 2285 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2286 this = self.sql(expression, "this") 2287 2288 args = [ 2289 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2290 for e in (expression.args.get(k) for k in ("offset", "expression")) 2291 if e 2292 ] 2293 2294 args_sql = ", ".join(self.sql(e) for e in args) 2295 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2296 expressions = self.expressions(expression, flat=True) 2297 limit_options = self.sql(expression, "limit_options") 2298 expressions = f" BY {expressions}" if expressions else "" 2299 2300 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2301 2302 def offset_sql(self, expression: exp.Offset) -> str: 2303 this = self.sql(expression, "this") 2304 value = expression.expression 2305 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2306 expressions = self.expressions(expression, flat=True) 2307 expressions = f" BY {expressions}" if expressions else "" 2308 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2309 2310 def setitem_sql(self, expression: exp.SetItem) -> str: 2311 kind = self.sql(expression, "kind") 2312 kind = f"{kind} " if kind else "" 2313 this = self.sql(expression, "this") 2314 expressions = self.expressions(expression) 2315 collate = self.sql(expression, "collate") 2316 collate = f" COLLATE {collate}" if collate else "" 2317 global_ = "GLOBAL " if expression.args.get("global") else "" 2318 return f"{global_}{kind}{this}{expressions}{collate}" 2319 2320 def set_sql(self, expression: exp.Set) -> str: 2321 expressions = f" {self.expressions(expression, flat=True)}" 2322 tag = " TAG" if expression.args.get("tag") else "" 2323 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2324 2325 def pragma_sql(self, expression: exp.Pragma) -> str: 2326 return f"PRAGMA {self.sql(expression, 'this')}" 2327 2328 def lock_sql(self, expression: exp.Lock) -> str: 2329 if not self.LOCKING_READS_SUPPORTED: 2330 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2331 return "" 2332 2333 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2334 expressions = self.expressions(expression, flat=True) 2335 expressions = f" OF {expressions}" if expressions else "" 2336 wait = expression.args.get("wait") 2337 2338 if wait is not None: 2339 if isinstance(wait, exp.Literal): 2340 wait = f" WAIT {self.sql(wait)}" 2341 else: 2342 wait = " NOWAIT" if wait else " SKIP LOCKED" 2343 2344 return f"{lock_type}{expressions}{wait or ''}" 2345 2346 def literal_sql(self, expression: exp.Literal) -> str: 2347 text = expression.this or "" 2348 if expression.is_string: 2349 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2350 return text 2351 2352 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2353 if self.dialect.ESCAPED_SEQUENCES: 2354 to_escaped = self.dialect.ESCAPED_SEQUENCES 2355 text = "".join( 2356 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2357 ) 2358 2359 return self._replace_line_breaks(text).replace( 2360 self.dialect.QUOTE_END, self._escaped_quote_end 2361 ) 2362 2363 def loaddata_sql(self, expression: exp.LoadData) -> str: 2364 local = " LOCAL" if expression.args.get("local") else "" 2365 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2366 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2367 this = f" INTO TABLE {self.sql(expression, 'this')}" 2368 partition = self.sql(expression, "partition") 2369 partition = f" {partition}" if partition else "" 2370 input_format = self.sql(expression, "input_format") 2371 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2372 serde = self.sql(expression, "serde") 2373 serde = f" SERDE {serde}" if serde else "" 2374 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2375 2376 def null_sql(self, *_) -> str: 2377 return "NULL" 2378 2379 def boolean_sql(self, expression: exp.Boolean) -> str: 2380 return "TRUE" if expression.this else "FALSE" 2381 2382 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2383 this = self.sql(expression, "this") 2384 this = f"{this} " if this else this 2385 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2386 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2387 2388 def withfill_sql(self, expression: exp.WithFill) -> str: 2389 from_sql = self.sql(expression, "from") 2390 from_sql = f" FROM {from_sql}" if from_sql else "" 2391 to_sql = self.sql(expression, "to") 2392 to_sql = f" TO {to_sql}" if to_sql else "" 2393 step_sql = self.sql(expression, "step") 2394 step_sql = f" STEP {step_sql}" if step_sql else "" 2395 interpolated_values = [ 2396 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2397 if isinstance(e, exp.Alias) 2398 else self.sql(e, "this") 2399 for e in expression.args.get("interpolate") or [] 2400 ] 2401 interpolate = ( 2402 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2403 ) 2404 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2405 2406 def cluster_sql(self, expression: exp.Cluster) -> str: 2407 return self.op_expressions("CLUSTER BY", expression) 2408 2409 def distribute_sql(self, expression: exp.Distribute) -> str: 2410 return self.op_expressions("DISTRIBUTE BY", expression) 2411 2412 def sort_sql(self, expression: exp.Sort) -> str: 2413 return self.op_expressions("SORT BY", expression) 2414 2415 def ordered_sql(self, expression: exp.Ordered) -> str: 2416 desc = expression.args.get("desc") 2417 asc = not desc 2418 2419 nulls_first = expression.args.get("nulls_first") 2420 nulls_last = not nulls_first 2421 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2422 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2423 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2424 2425 this = self.sql(expression, "this") 2426 2427 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2428 nulls_sort_change = "" 2429 if nulls_first and ( 2430 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2431 ): 2432 nulls_sort_change = " NULLS FIRST" 2433 elif ( 2434 nulls_last 2435 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2436 and not nulls_are_last 2437 ): 2438 nulls_sort_change = " NULLS LAST" 2439 2440 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2441 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2442 window = expression.find_ancestor(exp.Window, exp.Select) 2443 if isinstance(window, exp.Window) and window.args.get("spec"): 2444 self.unsupported( 2445 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2446 ) 2447 nulls_sort_change = "" 2448 elif self.NULL_ORDERING_SUPPORTED is False and ( 2449 (asc and nulls_sort_change == " NULLS LAST") 2450 or (desc and nulls_sort_change == " NULLS FIRST") 2451 ): 2452 # BigQuery does not allow these ordering/nulls combinations when used under 2453 # an aggregation func or under a window containing one 2454 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2455 2456 if isinstance(ancestor, exp.Window): 2457 ancestor = ancestor.this 2458 if isinstance(ancestor, exp.AggFunc): 2459 self.unsupported( 2460 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2461 ) 2462 nulls_sort_change = "" 2463 elif self.NULL_ORDERING_SUPPORTED is None: 2464 if expression.this.is_int: 2465 self.unsupported( 2466 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2467 ) 2468 elif not isinstance(expression.this, exp.Rand): 2469 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2470 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2471 nulls_sort_change = "" 2472 2473 with_fill = self.sql(expression, "with_fill") 2474 with_fill = f" {with_fill}" if with_fill else "" 2475 2476 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2477 2478 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2479 window_frame = self.sql(expression, "window_frame") 2480 window_frame = f"{window_frame} " if window_frame else "" 2481 2482 this = self.sql(expression, "this") 2483 2484 return f"{window_frame}{this}" 2485 2486 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2487 partition = self.partition_by_sql(expression) 2488 order = self.sql(expression, "order") 2489 measures = self.expressions(expression, key="measures") 2490 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2491 rows = self.sql(expression, "rows") 2492 rows = self.seg(rows) if rows else "" 2493 after = self.sql(expression, "after") 2494 after = self.seg(after) if after else "" 2495 pattern = self.sql(expression, "pattern") 2496 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2497 definition_sqls = [ 2498 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2499 for definition in expression.args.get("define", []) 2500 ] 2501 definitions = self.expressions(sqls=definition_sqls) 2502 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2503 body = "".join( 2504 ( 2505 partition, 2506 order, 2507 measures, 2508 rows, 2509 after, 2510 pattern, 2511 define, 2512 ) 2513 ) 2514 alias = self.sql(expression, "alias") 2515 alias = f" {alias}" if alias else "" 2516 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2517 2518 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2519 limit = expression.args.get("limit") 2520 2521 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2522 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2523 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2524 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2525 2526 return csv( 2527 *sqls, 2528 *[self.sql(join) for join in expression.args.get("joins") or []], 2529 self.sql(expression, "match"), 2530 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2531 self.sql(expression, "prewhere"), 2532 self.sql(expression, "where"), 2533 self.sql(expression, "connect"), 2534 self.sql(expression, "group"), 2535 self.sql(expression, "having"), 2536 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2537 self.sql(expression, "order"), 2538 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2539 *self.after_limit_modifiers(expression), 2540 self.options_modifier(expression), 2541 sep="", 2542 ) 2543 2544 def options_modifier(self, expression: exp.Expression) -> str: 2545 options = self.expressions(expression, key="options") 2546 return f" {options}" if options else "" 2547 2548 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2549 return "" 2550 2551 def offset_limit_modifiers( 2552 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2553 ) -> t.List[str]: 2554 return [ 2555 self.sql(expression, "offset") if fetch else self.sql(limit), 2556 self.sql(limit) if fetch else self.sql(expression, "offset"), 2557 ] 2558 2559 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2560 locks = self.expressions(expression, key="locks", sep=" ") 2561 locks = f" {locks}" if locks else "" 2562 return [locks, self.sql(expression, "sample")] 2563 2564 def select_sql(self, expression: exp.Select) -> str: 2565 into = expression.args.get("into") 2566 if not self.SUPPORTS_SELECT_INTO and into: 2567 into.pop() 2568 2569 hint = self.sql(expression, "hint") 2570 distinct = self.sql(expression, "distinct") 2571 distinct = f" {distinct}" if distinct else "" 2572 kind = self.sql(expression, "kind") 2573 2574 limit = expression.args.get("limit") 2575 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2576 top = self.limit_sql(limit, top=True) 2577 limit.pop() 2578 else: 2579 top = "" 2580 2581 expressions = self.expressions(expression) 2582 2583 if kind: 2584 if kind in self.SELECT_KINDS: 2585 kind = f" AS {kind}" 2586 else: 2587 if kind == "STRUCT": 2588 expressions = self.expressions( 2589 sqls=[ 2590 self.sql( 2591 exp.Struct( 2592 expressions=[ 2593 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2594 if isinstance(e, exp.Alias) 2595 else e 2596 for e in expression.expressions 2597 ] 2598 ) 2599 ) 2600 ] 2601 ) 2602 kind = "" 2603 2604 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2605 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2606 2607 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2608 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2609 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2610 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2611 sql = self.query_modifiers( 2612 expression, 2613 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2614 self.sql(expression, "into", comment=False), 2615 self.sql(expression, "from", comment=False), 2616 ) 2617 2618 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2619 if expression.args.get("with"): 2620 sql = self.maybe_comment(sql, expression) 2621 expression.pop_comments() 2622 2623 sql = self.prepend_ctes(expression, sql) 2624 2625 if not self.SUPPORTS_SELECT_INTO and into: 2626 if into.args.get("temporary"): 2627 table_kind = " TEMPORARY" 2628 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2629 table_kind = " UNLOGGED" 2630 else: 2631 table_kind = "" 2632 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2633 2634 return sql 2635 2636 def schema_sql(self, expression: exp.Schema) -> str: 2637 this = self.sql(expression, "this") 2638 sql = self.schema_columns_sql(expression) 2639 return f"{this} {sql}" if this and sql else this or sql 2640 2641 def schema_columns_sql(self, expression: exp.Schema) -> str: 2642 if expression.expressions: 2643 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2644 return "" 2645 2646 def star_sql(self, expression: exp.Star) -> str: 2647 except_ = self.expressions(expression, key="except", flat=True) 2648 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2649 replace = self.expressions(expression, key="replace", flat=True) 2650 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2651 rename = self.expressions(expression, key="rename", flat=True) 2652 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2653 return f"*{except_}{replace}{rename}" 2654 2655 def parameter_sql(self, expression: exp.Parameter) -> str: 2656 this = self.sql(expression, "this") 2657 return f"{self.PARAMETER_TOKEN}{this}" 2658 2659 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2660 this = self.sql(expression, "this") 2661 kind = expression.text("kind") 2662 if kind: 2663 kind = f"{kind}." 2664 return f"@@{kind}{this}" 2665 2666 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2667 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2668 2669 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2670 alias = self.sql(expression, "alias") 2671 alias = f"{sep}{alias}" if alias else "" 2672 sample = self.sql(expression, "sample") 2673 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2674 alias = f"{sample}{alias}" 2675 2676 # Set to None so it's not generated again by self.query_modifiers() 2677 expression.set("sample", None) 2678 2679 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2680 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2681 return self.prepend_ctes(expression, sql) 2682 2683 def qualify_sql(self, expression: exp.Qualify) -> str: 2684 this = self.indent(self.sql(expression, "this")) 2685 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2686 2687 def unnest_sql(self, expression: exp.Unnest) -> str: 2688 args = self.expressions(expression, flat=True) 2689 2690 alias = expression.args.get("alias") 2691 offset = expression.args.get("offset") 2692 2693 if self.UNNEST_WITH_ORDINALITY: 2694 if alias and isinstance(offset, exp.Expression): 2695 alias.append("columns", offset) 2696 2697 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2698 columns = alias.columns 2699 alias = self.sql(columns[0]) if columns else "" 2700 else: 2701 alias = self.sql(alias) 2702 2703 alias = f" AS {alias}" if alias else alias 2704 if self.UNNEST_WITH_ORDINALITY: 2705 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2706 else: 2707 if isinstance(offset, exp.Expression): 2708 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2709 elif offset: 2710 suffix = f"{alias} WITH OFFSET" 2711 else: 2712 suffix = alias 2713 2714 return f"UNNEST({args}){suffix}" 2715 2716 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2717 return "" 2718 2719 def where_sql(self, expression: exp.Where) -> str: 2720 this = self.indent(self.sql(expression, "this")) 2721 return f"{self.seg('WHERE')}{self.sep()}{this}" 2722 2723 def window_sql(self, expression: exp.Window) -> str: 2724 this = self.sql(expression, "this") 2725 partition = self.partition_by_sql(expression) 2726 order = expression.args.get("order") 2727 order = self.order_sql(order, flat=True) if order else "" 2728 spec = self.sql(expression, "spec") 2729 alias = self.sql(expression, "alias") 2730 over = self.sql(expression, "over") or "OVER" 2731 2732 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2733 2734 first = expression.args.get("first") 2735 if first is None: 2736 first = "" 2737 else: 2738 first = "FIRST" if first else "LAST" 2739 2740 if not partition and not order and not spec and alias: 2741 return f"{this} {alias}" 2742 2743 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2744 return f"{this} ({args})" 2745 2746 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2747 partition = self.expressions(expression, key="partition_by", flat=True) 2748 return f"PARTITION BY {partition}" if partition else "" 2749 2750 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2751 kind = self.sql(expression, "kind") 2752 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2753 end = ( 2754 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2755 or "CURRENT ROW" 2756 ) 2757 return f"{kind} BETWEEN {start} AND {end}" 2758 2759 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2760 this = self.sql(expression, "this") 2761 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2762 return f"{this} WITHIN GROUP ({expression_sql})" 2763 2764 def between_sql(self, expression: exp.Between) -> str: 2765 this = self.sql(expression, "this") 2766 low = self.sql(expression, "low") 2767 high = self.sql(expression, "high") 2768 return f"{this} BETWEEN {low} AND {high}" 2769 2770 def bracket_offset_expressions( 2771 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2772 ) -> t.List[exp.Expression]: 2773 return apply_index_offset( 2774 expression.this, 2775 expression.expressions, 2776 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2777 ) 2778 2779 def bracket_sql(self, expression: exp.Bracket) -> str: 2780 expressions = self.bracket_offset_expressions(expression) 2781 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2782 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2783 2784 def all_sql(self, expression: exp.All) -> str: 2785 return f"ALL {self.wrap(expression)}" 2786 2787 def any_sql(self, expression: exp.Any) -> str: 2788 this = self.sql(expression, "this") 2789 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2790 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2791 this = self.wrap(this) 2792 return f"ANY{this}" 2793 return f"ANY {this}" 2794 2795 def exists_sql(self, expression: exp.Exists) -> str: 2796 return f"EXISTS{self.wrap(expression)}" 2797 2798 def case_sql(self, expression: exp.Case) -> str: 2799 this = self.sql(expression, "this") 2800 statements = [f"CASE {this}" if this else "CASE"] 2801 2802 for e in expression.args["ifs"]: 2803 statements.append(f"WHEN {self.sql(e, 'this')}") 2804 statements.append(f"THEN {self.sql(e, 'true')}") 2805 2806 default = self.sql(expression, "default") 2807 2808 if default: 2809 statements.append(f"ELSE {default}") 2810 2811 statements.append("END") 2812 2813 if self.pretty and self.too_wide(statements): 2814 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2815 2816 return " ".join(statements) 2817 2818 def constraint_sql(self, expression: exp.Constraint) -> str: 2819 this = self.sql(expression, "this") 2820 expressions = self.expressions(expression, flat=True) 2821 return f"CONSTRAINT {this} {expressions}" 2822 2823 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2824 order = expression.args.get("order") 2825 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2826 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2827 2828 def extract_sql(self, expression: exp.Extract) -> str: 2829 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2830 expression_sql = self.sql(expression, "expression") 2831 return f"EXTRACT({this} FROM {expression_sql})" 2832 2833 def trim_sql(self, expression: exp.Trim) -> str: 2834 trim_type = self.sql(expression, "position") 2835 2836 if trim_type == "LEADING": 2837 func_name = "LTRIM" 2838 elif trim_type == "TRAILING": 2839 func_name = "RTRIM" 2840 else: 2841 func_name = "TRIM" 2842 2843 return self.func(func_name, expression.this, expression.expression) 2844 2845 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2846 args = expression.expressions 2847 if isinstance(expression, exp.ConcatWs): 2848 args = args[1:] # Skip the delimiter 2849 2850 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2851 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2852 2853 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2854 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2855 2856 return args 2857 2858 def concat_sql(self, expression: exp.Concat) -> str: 2859 expressions = self.convert_concat_args(expression) 2860 2861 # Some dialects don't allow a single-argument CONCAT call 2862 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2863 return self.sql(expressions[0]) 2864 2865 return self.func("CONCAT", *expressions) 2866 2867 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2868 return self.func( 2869 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2870 ) 2871 2872 def check_sql(self, expression: exp.Check) -> str: 2873 this = self.sql(expression, key="this") 2874 return f"CHECK ({this})" 2875 2876 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2877 expressions = self.expressions(expression, flat=True) 2878 expressions = f" ({expressions})" if expressions else "" 2879 reference = self.sql(expression, "reference") 2880 reference = f" {reference}" if reference else "" 2881 delete = self.sql(expression, "delete") 2882 delete = f" ON DELETE {delete}" if delete else "" 2883 update = self.sql(expression, "update") 2884 update = f" ON UPDATE {update}" if update else "" 2885 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2886 2887 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2888 expressions = self.expressions(expression, flat=True) 2889 options = self.expressions(expression, key="options", flat=True, sep=" ") 2890 options = f" {options}" if options else "" 2891 return f"PRIMARY KEY ({expressions}){options}" 2892 2893 def if_sql(self, expression: exp.If) -> str: 2894 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2895 2896 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2897 modifier = expression.args.get("modifier") 2898 modifier = f" {modifier}" if modifier else "" 2899 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2900 2901 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2902 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2903 2904 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2905 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2906 2907 if expression.args.get("escape"): 2908 path = self.escape_str(path) 2909 2910 if self.QUOTE_JSON_PATH: 2911 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2912 2913 return path 2914 2915 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2916 if isinstance(expression, exp.JSONPathPart): 2917 transform = self.TRANSFORMS.get(expression.__class__) 2918 if not callable(transform): 2919 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2920 return "" 2921 2922 return transform(self, expression) 2923 2924 if isinstance(expression, int): 2925 return str(expression) 2926 2927 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2928 escaped = expression.replace("'", "\\'") 2929 escaped = f"\\'{expression}\\'" 2930 else: 2931 escaped = expression.replace('"', '\\"') 2932 escaped = f'"{escaped}"' 2933 2934 return escaped 2935 2936 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2937 return f"{self.sql(expression, 'this')} FORMAT JSON" 2938 2939 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2940 null_handling = expression.args.get("null_handling") 2941 null_handling = f" {null_handling}" if null_handling else "" 2942 2943 unique_keys = expression.args.get("unique_keys") 2944 if unique_keys is not None: 2945 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2946 else: 2947 unique_keys = "" 2948 2949 return_type = self.sql(expression, "return_type") 2950 return_type = f" RETURNING {return_type}" if return_type else "" 2951 encoding = self.sql(expression, "encoding") 2952 encoding = f" ENCODING {encoding}" if encoding else "" 2953 2954 return self.func( 2955 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2956 *expression.expressions, 2957 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2958 ) 2959 2960 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2961 return self.jsonobject_sql(expression) 2962 2963 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2964 null_handling = expression.args.get("null_handling") 2965 null_handling = f" {null_handling}" if null_handling else "" 2966 return_type = self.sql(expression, "return_type") 2967 return_type = f" RETURNING {return_type}" if return_type else "" 2968 strict = " STRICT" if expression.args.get("strict") else "" 2969 return self.func( 2970 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2971 ) 2972 2973 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2974 this = self.sql(expression, "this") 2975 order = self.sql(expression, "order") 2976 null_handling = expression.args.get("null_handling") 2977 null_handling = f" {null_handling}" if null_handling else "" 2978 return_type = self.sql(expression, "return_type") 2979 return_type = f" RETURNING {return_type}" if return_type else "" 2980 strict = " STRICT" if expression.args.get("strict") else "" 2981 return self.func( 2982 "JSON_ARRAYAGG", 2983 this, 2984 suffix=f"{order}{null_handling}{return_type}{strict})", 2985 ) 2986 2987 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2988 path = self.sql(expression, "path") 2989 path = f" PATH {path}" if path else "" 2990 nested_schema = self.sql(expression, "nested_schema") 2991 2992 if nested_schema: 2993 return f"NESTED{path} {nested_schema}" 2994 2995 this = self.sql(expression, "this") 2996 kind = self.sql(expression, "kind") 2997 kind = f" {kind}" if kind else "" 2998 return f"{this}{kind}{path}" 2999 3000 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3001 return self.func("COLUMNS", *expression.expressions) 3002 3003 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3004 this = self.sql(expression, "this") 3005 path = self.sql(expression, "path") 3006 path = f", {path}" if path else "" 3007 error_handling = expression.args.get("error_handling") 3008 error_handling = f" {error_handling}" if error_handling else "" 3009 empty_handling = expression.args.get("empty_handling") 3010 empty_handling = f" {empty_handling}" if empty_handling else "" 3011 schema = self.sql(expression, "schema") 3012 return self.func( 3013 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3014 ) 3015 3016 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3017 this = self.sql(expression, "this") 3018 kind = self.sql(expression, "kind") 3019 path = self.sql(expression, "path") 3020 path = f" {path}" if path else "" 3021 as_json = " AS JSON" if expression.args.get("as_json") else "" 3022 return f"{this} {kind}{path}{as_json}" 3023 3024 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3025 this = self.sql(expression, "this") 3026 path = self.sql(expression, "path") 3027 path = f", {path}" if path else "" 3028 expressions = self.expressions(expression) 3029 with_ = ( 3030 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3031 if expressions 3032 else "" 3033 ) 3034 return f"OPENJSON({this}{path}){with_}" 3035 3036 def in_sql(self, expression: exp.In) -> str: 3037 query = expression.args.get("query") 3038 unnest = expression.args.get("unnest") 3039 field = expression.args.get("field") 3040 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3041 3042 if query: 3043 in_sql = self.sql(query) 3044 elif unnest: 3045 in_sql = self.in_unnest_op(unnest) 3046 elif field: 3047 in_sql = self.sql(field) 3048 else: 3049 in_sql = f"({self.expressions(expression, flat=True)})" 3050 3051 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3052 3053 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3054 return f"(SELECT {self.sql(unnest)})" 3055 3056 def interval_sql(self, expression: exp.Interval) -> str: 3057 unit = self.sql(expression, "unit") 3058 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3059 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3060 unit = f" {unit}" if unit else "" 3061 3062 if self.SINGLE_STRING_INTERVAL: 3063 this = expression.this.name if expression.this else "" 3064 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3065 3066 this = self.sql(expression, "this") 3067 if this: 3068 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3069 this = f" {this}" if unwrapped else f" ({this})" 3070 3071 return f"INTERVAL{this}{unit}" 3072 3073 def return_sql(self, expression: exp.Return) -> str: 3074 return f"RETURN {self.sql(expression, 'this')}" 3075 3076 def reference_sql(self, expression: exp.Reference) -> str: 3077 this = self.sql(expression, "this") 3078 expressions = self.expressions(expression, flat=True) 3079 expressions = f"({expressions})" if expressions else "" 3080 options = self.expressions(expression, key="options", flat=True, sep=" ") 3081 options = f" {options}" if options else "" 3082 return f"REFERENCES {this}{expressions}{options}" 3083 3084 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3085 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3086 parent = expression.parent 3087 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3088 return self.func( 3089 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3090 ) 3091 3092 def paren_sql(self, expression: exp.Paren) -> str: 3093 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3094 return f"({sql}{self.seg(')', sep='')}" 3095 3096 def neg_sql(self, expression: exp.Neg) -> str: 3097 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3098 this_sql = self.sql(expression, "this") 3099 sep = " " if this_sql[0] == "-" else "" 3100 return f"-{sep}{this_sql}" 3101 3102 def not_sql(self, expression: exp.Not) -> str: 3103 return f"NOT {self.sql(expression, 'this')}" 3104 3105 def alias_sql(self, expression: exp.Alias) -> str: 3106 alias = self.sql(expression, "alias") 3107 alias = f" AS {alias}" if alias else "" 3108 return f"{self.sql(expression, 'this')}{alias}" 3109 3110 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3111 alias = expression.args["alias"] 3112 3113 identifier_alias = isinstance(alias, exp.Identifier) 3114 literal_alias = isinstance(alias, exp.Literal) 3115 3116 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3117 alias.replace(exp.Literal.string(alias.output_name)) 3118 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3119 alias.replace(exp.to_identifier(alias.output_name)) 3120 3121 return self.alias_sql(expression) 3122 3123 def aliases_sql(self, expression: exp.Aliases) -> str: 3124 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3125 3126 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3127 this = self.sql(expression, "this") 3128 index = self.sql(expression, "expression") 3129 return f"{this} AT {index}" 3130 3131 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3132 this = self.sql(expression, "this") 3133 zone = self.sql(expression, "zone") 3134 return f"{this} AT TIME ZONE {zone}" 3135 3136 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3137 this = self.sql(expression, "this") 3138 zone = self.sql(expression, "zone") 3139 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3140 3141 def add_sql(self, expression: exp.Add) -> str: 3142 return self.binary(expression, "+") 3143 3144 def and_sql( 3145 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3146 ) -> str: 3147 return self.connector_sql(expression, "AND", stack) 3148 3149 def or_sql( 3150 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3151 ) -> str: 3152 return self.connector_sql(expression, "OR", stack) 3153 3154 def xor_sql( 3155 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3156 ) -> str: 3157 return self.connector_sql(expression, "XOR", stack) 3158 3159 def connector_sql( 3160 self, 3161 expression: exp.Connector, 3162 op: str, 3163 stack: t.Optional[t.List[str | exp.Expression]] = None, 3164 ) -> str: 3165 if stack is not None: 3166 if expression.expressions: 3167 stack.append(self.expressions(expression, sep=f" {op} ")) 3168 else: 3169 stack.append(expression.right) 3170 if expression.comments and self.comments: 3171 for comment in expression.comments: 3172 if comment: 3173 op += f" /*{self.pad_comment(comment)}*/" 3174 stack.extend((op, expression.left)) 3175 return op 3176 3177 stack = [expression] 3178 sqls: t.List[str] = [] 3179 ops = set() 3180 3181 while stack: 3182 node = stack.pop() 3183 if isinstance(node, exp.Connector): 3184 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3185 else: 3186 sql = self.sql(node) 3187 if sqls and sqls[-1] in ops: 3188 sqls[-1] += f" {sql}" 3189 else: 3190 sqls.append(sql) 3191 3192 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3193 return sep.join(sqls) 3194 3195 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3196 return self.binary(expression, "&") 3197 3198 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3199 return self.binary(expression, "<<") 3200 3201 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3202 return f"~{self.sql(expression, 'this')}" 3203 3204 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3205 return self.binary(expression, "|") 3206 3207 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3208 return self.binary(expression, ">>") 3209 3210 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3211 return self.binary(expression, "^") 3212 3213 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3214 format_sql = self.sql(expression, "format") 3215 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3216 to_sql = self.sql(expression, "to") 3217 to_sql = f" {to_sql}" if to_sql else "" 3218 action = self.sql(expression, "action") 3219 action = f" {action}" if action else "" 3220 default = self.sql(expression, "default") 3221 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3222 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3223 3224 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3225 zone = self.sql(expression, "this") 3226 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3227 3228 def collate_sql(self, expression: exp.Collate) -> str: 3229 if self.COLLATE_IS_FUNC: 3230 return self.function_fallback_sql(expression) 3231 return self.binary(expression, "COLLATE") 3232 3233 def command_sql(self, expression: exp.Command) -> str: 3234 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3235 3236 def comment_sql(self, expression: exp.Comment) -> str: 3237 this = self.sql(expression, "this") 3238 kind = expression.args["kind"] 3239 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3240 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3241 expression_sql = self.sql(expression, "expression") 3242 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3243 3244 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3245 this = self.sql(expression, "this") 3246 delete = " DELETE" if expression.args.get("delete") else "" 3247 recompress = self.sql(expression, "recompress") 3248 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3249 to_disk = self.sql(expression, "to_disk") 3250 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3251 to_volume = self.sql(expression, "to_volume") 3252 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3253 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3254 3255 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3256 where = self.sql(expression, "where") 3257 group = self.sql(expression, "group") 3258 aggregates = self.expressions(expression, key="aggregates") 3259 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3260 3261 if not (where or group or aggregates) and len(expression.expressions) == 1: 3262 return f"TTL {self.expressions(expression, flat=True)}" 3263 3264 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3265 3266 def transaction_sql(self, expression: exp.Transaction) -> str: 3267 return "BEGIN" 3268 3269 def commit_sql(self, expression: exp.Commit) -> str: 3270 chain = expression.args.get("chain") 3271 if chain is not None: 3272 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3273 3274 return f"COMMIT{chain or ''}" 3275 3276 def rollback_sql(self, expression: exp.Rollback) -> str: 3277 savepoint = expression.args.get("savepoint") 3278 savepoint = f" TO {savepoint}" if savepoint else "" 3279 return f"ROLLBACK{savepoint}" 3280 3281 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3282 this = self.sql(expression, "this") 3283 3284 dtype = self.sql(expression, "dtype") 3285 if dtype: 3286 collate = self.sql(expression, "collate") 3287 collate = f" COLLATE {collate}" if collate else "" 3288 using = self.sql(expression, "using") 3289 using = f" USING {using}" if using else "" 3290 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3291 3292 default = self.sql(expression, "default") 3293 if default: 3294 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3295 3296 comment = self.sql(expression, "comment") 3297 if comment: 3298 return f"ALTER COLUMN {this} COMMENT {comment}" 3299 3300 visible = expression.args.get("visible") 3301 if visible: 3302 return f"ALTER COLUMN {this} SET {visible}" 3303 3304 allow_null = expression.args.get("allow_null") 3305 drop = expression.args.get("drop") 3306 3307 if not drop and not allow_null: 3308 self.unsupported("Unsupported ALTER COLUMN syntax") 3309 3310 if allow_null is not None: 3311 keyword = "DROP" if drop else "SET" 3312 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3313 3314 return f"ALTER COLUMN {this} DROP DEFAULT" 3315 3316 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3317 this = self.sql(expression, "this") 3318 3319 visible = expression.args.get("visible") 3320 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3321 3322 return f"ALTER INDEX {this} {visible_sql}" 3323 3324 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3325 this = self.sql(expression, "this") 3326 if not isinstance(expression.this, exp.Var): 3327 this = f"KEY DISTKEY {this}" 3328 return f"ALTER DISTSTYLE {this}" 3329 3330 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3331 compound = " COMPOUND" if expression.args.get("compound") else "" 3332 this = self.sql(expression, "this") 3333 expressions = self.expressions(expression, flat=True) 3334 expressions = f"({expressions})" if expressions else "" 3335 return f"ALTER{compound} SORTKEY {this or expressions}" 3336 3337 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3338 if not self.RENAME_TABLE_WITH_DB: 3339 # Remove db from tables 3340 expression = expression.transform( 3341 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3342 ).assert_is(exp.AlterRename) 3343 this = self.sql(expression, "this") 3344 return f"RENAME TO {this}" 3345 3346 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3347 exists = " IF EXISTS" if expression.args.get("exists") else "" 3348 old_column = self.sql(expression, "this") 3349 new_column = self.sql(expression, "to") 3350 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3351 3352 def alterset_sql(self, expression: exp.AlterSet) -> str: 3353 exprs = self.expressions(expression, flat=True) 3354 return f"SET {exprs}" 3355 3356 def alter_sql(self, expression: exp.Alter) -> str: 3357 actions = expression.args["actions"] 3358 3359 if isinstance(actions[0], exp.ColumnDef): 3360 actions = self.add_column_sql(expression) 3361 elif isinstance(actions[0], exp.Schema): 3362 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3363 elif isinstance(actions[0], exp.Delete): 3364 actions = self.expressions(expression, key="actions", flat=True) 3365 elif isinstance(actions[0], exp.Query): 3366 actions = "AS " + self.expressions(expression, key="actions") 3367 else: 3368 actions = self.expressions(expression, key="actions", flat=True) 3369 3370 exists = " IF EXISTS" if expression.args.get("exists") else "" 3371 on_cluster = self.sql(expression, "cluster") 3372 on_cluster = f" {on_cluster}" if on_cluster else "" 3373 only = " ONLY" if expression.args.get("only") else "" 3374 options = self.expressions(expression, key="options") 3375 options = f", {options}" if options else "" 3376 kind = self.sql(expression, "kind") 3377 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3378 3379 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3380 3381 def add_column_sql(self, expression: exp.Alter) -> str: 3382 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3383 return self.expressions( 3384 expression, 3385 key="actions", 3386 prefix="ADD COLUMN ", 3387 skip_first=True, 3388 ) 3389 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3390 3391 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3392 expressions = self.expressions(expression) 3393 exists = " IF EXISTS " if expression.args.get("exists") else " " 3394 return f"DROP{exists}{expressions}" 3395 3396 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3397 return f"ADD {self.expressions(expression)}" 3398 3399 def distinct_sql(self, expression: exp.Distinct) -> str: 3400 this = self.expressions(expression, flat=True) 3401 3402 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3403 case = exp.case() 3404 for arg in expression.expressions: 3405 case = case.when(arg.is_(exp.null()), exp.null()) 3406 this = self.sql(case.else_(f"({this})")) 3407 3408 this = f" {this}" if this else "" 3409 3410 on = self.sql(expression, "on") 3411 on = f" ON {on}" if on else "" 3412 return f"DISTINCT{this}{on}" 3413 3414 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3415 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3416 3417 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3418 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3419 3420 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3421 this_sql = self.sql(expression, "this") 3422 expression_sql = self.sql(expression, "expression") 3423 kind = "MAX" if expression.args.get("max") else "MIN" 3424 return f"{this_sql} HAVING {kind} {expression_sql}" 3425 3426 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3427 return self.sql( 3428 exp.Cast( 3429 this=exp.Div(this=expression.this, expression=expression.expression), 3430 to=exp.DataType(this=exp.DataType.Type.INT), 3431 ) 3432 ) 3433 3434 def dpipe_sql(self, expression: exp.DPipe) -> str: 3435 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3436 return self.func( 3437 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3438 ) 3439 return self.binary(expression, "||") 3440 3441 def div_sql(self, expression: exp.Div) -> str: 3442 l, r = expression.left, expression.right 3443 3444 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3445 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3446 3447 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3448 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3449 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3450 3451 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3452 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3453 return self.sql( 3454 exp.cast( 3455 l / r, 3456 to=exp.DataType.Type.BIGINT, 3457 ) 3458 ) 3459 3460 return self.binary(expression, "/") 3461 3462 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3463 n = exp._wrap(expression.this, exp.Binary) 3464 d = exp._wrap(expression.expression, exp.Binary) 3465 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3466 3467 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3468 return self.binary(expression, "OVERLAPS") 3469 3470 def distance_sql(self, expression: exp.Distance) -> str: 3471 return self.binary(expression, "<->") 3472 3473 def dot_sql(self, expression: exp.Dot) -> str: 3474 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3475 3476 def eq_sql(self, expression: exp.EQ) -> str: 3477 return self.binary(expression, "=") 3478 3479 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3480 return self.binary(expression, ":=") 3481 3482 def escape_sql(self, expression: exp.Escape) -> str: 3483 return self.binary(expression, "ESCAPE") 3484 3485 def glob_sql(self, expression: exp.Glob) -> str: 3486 return self.binary(expression, "GLOB") 3487 3488 def gt_sql(self, expression: exp.GT) -> str: 3489 return self.binary(expression, ">") 3490 3491 def gte_sql(self, expression: exp.GTE) -> str: 3492 return self.binary(expression, ">=") 3493 3494 def ilike_sql(self, expression: exp.ILike) -> str: 3495 return self.binary(expression, "ILIKE") 3496 3497 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3498 return self.binary(expression, "ILIKE ANY") 3499 3500 def is_sql(self, expression: exp.Is) -> str: 3501 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3502 return self.sql( 3503 expression.this if expression.expression.this else exp.not_(expression.this) 3504 ) 3505 return self.binary(expression, "IS") 3506 3507 def like_sql(self, expression: exp.Like) -> str: 3508 return self.binary(expression, "LIKE") 3509 3510 def likeany_sql(self, expression: exp.LikeAny) -> str: 3511 return self.binary(expression, "LIKE ANY") 3512 3513 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3514 return self.binary(expression, "SIMILAR TO") 3515 3516 def lt_sql(self, expression: exp.LT) -> str: 3517 return self.binary(expression, "<") 3518 3519 def lte_sql(self, expression: exp.LTE) -> str: 3520 return self.binary(expression, "<=") 3521 3522 def mod_sql(self, expression: exp.Mod) -> str: 3523 return self.binary(expression, "%") 3524 3525 def mul_sql(self, expression: exp.Mul) -> str: 3526 return self.binary(expression, "*") 3527 3528 def neq_sql(self, expression: exp.NEQ) -> str: 3529 return self.binary(expression, "<>") 3530 3531 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3532 return self.binary(expression, "IS NOT DISTINCT FROM") 3533 3534 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3535 return self.binary(expression, "IS DISTINCT FROM") 3536 3537 def slice_sql(self, expression: exp.Slice) -> str: 3538 return self.binary(expression, ":") 3539 3540 def sub_sql(self, expression: exp.Sub) -> str: 3541 return self.binary(expression, "-") 3542 3543 def trycast_sql(self, expression: exp.TryCast) -> str: 3544 return self.cast_sql(expression, safe_prefix="TRY_") 3545 3546 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3547 return self.cast_sql(expression) 3548 3549 def try_sql(self, expression: exp.Try) -> str: 3550 if not self.TRY_SUPPORTED: 3551 self.unsupported("Unsupported TRY function") 3552 return self.sql(expression, "this") 3553 3554 return self.func("TRY", expression.this) 3555 3556 def log_sql(self, expression: exp.Log) -> str: 3557 this = expression.this 3558 expr = expression.expression 3559 3560 if self.dialect.LOG_BASE_FIRST is False: 3561 this, expr = expr, this 3562 elif self.dialect.LOG_BASE_FIRST is None and expr: 3563 if this.name in ("2", "10"): 3564 return self.func(f"LOG{this.name}", expr) 3565 3566 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3567 3568 return self.func("LOG", this, expr) 3569 3570 def use_sql(self, expression: exp.Use) -> str: 3571 kind = self.sql(expression, "kind") 3572 kind = f" {kind}" if kind else "" 3573 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3574 this = f" {this}" if this else "" 3575 return f"USE{kind}{this}" 3576 3577 def binary(self, expression: exp.Binary, op: str) -> str: 3578 sqls: t.List[str] = [] 3579 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3580 binary_type = type(expression) 3581 3582 while stack: 3583 node = stack.pop() 3584 3585 if type(node) is binary_type: 3586 op_func = node.args.get("operator") 3587 if op_func: 3588 op = f"OPERATOR({self.sql(op_func)})" 3589 3590 stack.append(node.right) 3591 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3592 stack.append(node.left) 3593 else: 3594 sqls.append(self.sql(node)) 3595 3596 return "".join(sqls) 3597 3598 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3599 to_clause = self.sql(expression, "to") 3600 if to_clause: 3601 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3602 3603 return self.function_fallback_sql(expression) 3604 3605 def function_fallback_sql(self, expression: exp.Func) -> str: 3606 args = [] 3607 3608 for key in expression.arg_types: 3609 arg_value = expression.args.get(key) 3610 3611 if isinstance(arg_value, list): 3612 for value in arg_value: 3613 args.append(value) 3614 elif arg_value is not None: 3615 args.append(arg_value) 3616 3617 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3618 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3619 else: 3620 name = expression.sql_name() 3621 3622 return self.func(name, *args) 3623 3624 def func( 3625 self, 3626 name: str, 3627 *args: t.Optional[exp.Expression | str], 3628 prefix: str = "(", 3629 suffix: str = ")", 3630 normalize: bool = True, 3631 ) -> str: 3632 name = self.normalize_func(name) if normalize else name 3633 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3634 3635 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3636 arg_sqls = tuple( 3637 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3638 ) 3639 if self.pretty and self.too_wide(arg_sqls): 3640 return self.indent( 3641 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3642 ) 3643 return sep.join(arg_sqls) 3644 3645 def too_wide(self, args: t.Iterable) -> bool: 3646 return sum(len(arg) for arg in args) > self.max_text_width 3647 3648 def format_time( 3649 self, 3650 expression: exp.Expression, 3651 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3652 inverse_time_trie: t.Optional[t.Dict] = None, 3653 ) -> t.Optional[str]: 3654 return format_time( 3655 self.sql(expression, "format"), 3656 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3657 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3658 ) 3659 3660 def expressions( 3661 self, 3662 expression: t.Optional[exp.Expression] = None, 3663 key: t.Optional[str] = None, 3664 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3665 flat: bool = False, 3666 indent: bool = True, 3667 skip_first: bool = False, 3668 skip_last: bool = False, 3669 sep: str = ", ", 3670 prefix: str = "", 3671 dynamic: bool = False, 3672 new_line: bool = False, 3673 ) -> str: 3674 expressions = expression.args.get(key or "expressions") if expression else sqls 3675 3676 if not expressions: 3677 return "" 3678 3679 if flat: 3680 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3681 3682 num_sqls = len(expressions) 3683 result_sqls = [] 3684 3685 for i, e in enumerate(expressions): 3686 sql = self.sql(e, comment=False) 3687 if not sql: 3688 continue 3689 3690 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3691 3692 if self.pretty: 3693 if self.leading_comma: 3694 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3695 else: 3696 result_sqls.append( 3697 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3698 ) 3699 else: 3700 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3701 3702 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3703 if new_line: 3704 result_sqls.insert(0, "") 3705 result_sqls.append("") 3706 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3707 else: 3708 result_sql = "".join(result_sqls) 3709 3710 return ( 3711 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3712 if indent 3713 else result_sql 3714 ) 3715 3716 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3717 flat = flat or isinstance(expression.parent, exp.Properties) 3718 expressions_sql = self.expressions(expression, flat=flat) 3719 if flat: 3720 return f"{op} {expressions_sql}" 3721 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3722 3723 def naked_property(self, expression: exp.Property) -> str: 3724 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3725 if not property_name: 3726 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3727 return f"{property_name} {self.sql(expression, 'this')}" 3728 3729 def tag_sql(self, expression: exp.Tag) -> str: 3730 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3731 3732 def token_sql(self, token_type: TokenType) -> str: 3733 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3734 3735 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3736 this = self.sql(expression, "this") 3737 expressions = self.no_identify(self.expressions, expression) 3738 expressions = ( 3739 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3740 ) 3741 return f"{this}{expressions}" if expressions.strip() != "" else this 3742 3743 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3744 this = self.sql(expression, "this") 3745 expressions = self.expressions(expression, flat=True) 3746 return f"{this}({expressions})" 3747 3748 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3749 return self.binary(expression, "=>") 3750 3751 def when_sql(self, expression: exp.When) -> str: 3752 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3753 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3754 condition = self.sql(expression, "condition") 3755 condition = f" AND {condition}" if condition else "" 3756 3757 then_expression = expression.args.get("then") 3758 if isinstance(then_expression, exp.Insert): 3759 this = self.sql(then_expression, "this") 3760 this = f"INSERT {this}" if this else "INSERT" 3761 then = self.sql(then_expression, "expression") 3762 then = f"{this} VALUES {then}" if then else this 3763 elif isinstance(then_expression, exp.Update): 3764 if isinstance(then_expression.args.get("expressions"), exp.Star): 3765 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3766 else: 3767 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3768 else: 3769 then = self.sql(then_expression) 3770 return f"WHEN {matched}{source}{condition} THEN {then}" 3771 3772 def whens_sql(self, expression: exp.Whens) -> str: 3773 return self.expressions(expression, sep=" ", indent=False) 3774 3775 def merge_sql(self, expression: exp.Merge) -> str: 3776 table = expression.this 3777 table_alias = "" 3778 3779 hints = table.args.get("hints") 3780 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3781 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3782 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3783 3784 this = self.sql(table) 3785 using = f"USING {self.sql(expression, 'using')}" 3786 on = f"ON {self.sql(expression, 'on')}" 3787 whens = self.sql(expression, "whens") 3788 3789 returning = self.sql(expression, "returning") 3790 if returning: 3791 whens = f"{whens}{returning}" 3792 3793 sep = self.sep() 3794 3795 return self.prepend_ctes( 3796 expression, 3797 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3798 ) 3799 3800 @unsupported_args("format") 3801 def tochar_sql(self, expression: exp.ToChar) -> str: 3802 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3803 3804 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3805 if not self.SUPPORTS_TO_NUMBER: 3806 self.unsupported("Unsupported TO_NUMBER function") 3807 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3808 3809 fmt = expression.args.get("format") 3810 if not fmt: 3811 self.unsupported("Conversion format is required for TO_NUMBER") 3812 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3813 3814 return self.func("TO_NUMBER", expression.this, fmt) 3815 3816 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3817 this = self.sql(expression, "this") 3818 kind = self.sql(expression, "kind") 3819 settings_sql = self.expressions(expression, key="settings", sep=" ") 3820 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3821 return f"{this}({kind}{args})" 3822 3823 def dictrange_sql(self, expression: exp.DictRange) -> str: 3824 this = self.sql(expression, "this") 3825 max = self.sql(expression, "max") 3826 min = self.sql(expression, "min") 3827 return f"{this}(MIN {min} MAX {max})" 3828 3829 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3830 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3831 3832 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3833 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3834 3835 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3836 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3837 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3838 3839 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3840 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3841 expressions = self.expressions(expression, flat=True) 3842 expressions = f" {self.wrap(expressions)}" if expressions else "" 3843 buckets = self.sql(expression, "buckets") 3844 kind = self.sql(expression, "kind") 3845 buckets = f" BUCKETS {buckets}" if buckets else "" 3846 order = self.sql(expression, "order") 3847 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3848 3849 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3850 return "" 3851 3852 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3853 expressions = self.expressions(expression, key="expressions", flat=True) 3854 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3855 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3856 buckets = self.sql(expression, "buckets") 3857 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3858 3859 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3860 this = self.sql(expression, "this") 3861 having = self.sql(expression, "having") 3862 3863 if having: 3864 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3865 3866 return self.func("ANY_VALUE", this) 3867 3868 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3869 transform = self.func("TRANSFORM", *expression.expressions) 3870 row_format_before = self.sql(expression, "row_format_before") 3871 row_format_before = f" {row_format_before}" if row_format_before else "" 3872 record_writer = self.sql(expression, "record_writer") 3873 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3874 using = f" USING {self.sql(expression, 'command_script')}" 3875 schema = self.sql(expression, "schema") 3876 schema = f" AS {schema}" if schema else "" 3877 row_format_after = self.sql(expression, "row_format_after") 3878 row_format_after = f" {row_format_after}" if row_format_after else "" 3879 record_reader = self.sql(expression, "record_reader") 3880 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3881 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3882 3883 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3884 key_block_size = self.sql(expression, "key_block_size") 3885 if key_block_size: 3886 return f"KEY_BLOCK_SIZE = {key_block_size}" 3887 3888 using = self.sql(expression, "using") 3889 if using: 3890 return f"USING {using}" 3891 3892 parser = self.sql(expression, "parser") 3893 if parser: 3894 return f"WITH PARSER {parser}" 3895 3896 comment = self.sql(expression, "comment") 3897 if comment: 3898 return f"COMMENT {comment}" 3899 3900 visible = expression.args.get("visible") 3901 if visible is not None: 3902 return "VISIBLE" if visible else "INVISIBLE" 3903 3904 engine_attr = self.sql(expression, "engine_attr") 3905 if engine_attr: 3906 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3907 3908 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3909 if secondary_engine_attr: 3910 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3911 3912 self.unsupported("Unsupported index constraint option.") 3913 return "" 3914 3915 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3916 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3917 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3918 3919 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3920 kind = self.sql(expression, "kind") 3921 kind = f"{kind} INDEX" if kind else "INDEX" 3922 this = self.sql(expression, "this") 3923 this = f" {this}" if this else "" 3924 index_type = self.sql(expression, "index_type") 3925 index_type = f" USING {index_type}" if index_type else "" 3926 expressions = self.expressions(expression, flat=True) 3927 expressions = f" ({expressions})" if expressions else "" 3928 options = self.expressions(expression, key="options", sep=" ") 3929 options = f" {options}" if options else "" 3930 return f"{kind}{this}{index_type}{expressions}{options}" 3931 3932 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3933 if self.NVL2_SUPPORTED: 3934 return self.function_fallback_sql(expression) 3935 3936 case = exp.Case().when( 3937 expression.this.is_(exp.null()).not_(copy=False), 3938 expression.args["true"], 3939 copy=False, 3940 ) 3941 else_cond = expression.args.get("false") 3942 if else_cond: 3943 case.else_(else_cond, copy=False) 3944 3945 return self.sql(case) 3946 3947 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3948 this = self.sql(expression, "this") 3949 expr = self.sql(expression, "expression") 3950 iterator = self.sql(expression, "iterator") 3951 condition = self.sql(expression, "condition") 3952 condition = f" IF {condition}" if condition else "" 3953 return f"{this} FOR {expr} IN {iterator}{condition}" 3954 3955 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3956 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3957 3958 def opclass_sql(self, expression: exp.Opclass) -> str: 3959 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3960 3961 def predict_sql(self, expression: exp.Predict) -> str: 3962 model = self.sql(expression, "this") 3963 model = f"MODEL {model}" 3964 table = self.sql(expression, "expression") 3965 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3966 parameters = self.sql(expression, "params_struct") 3967 return self.func("PREDICT", model, table, parameters or None) 3968 3969 def forin_sql(self, expression: exp.ForIn) -> str: 3970 this = self.sql(expression, "this") 3971 expression_sql = self.sql(expression, "expression") 3972 return f"FOR {this} DO {expression_sql}" 3973 3974 def refresh_sql(self, expression: exp.Refresh) -> str: 3975 this = self.sql(expression, "this") 3976 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3977 return f"REFRESH {table}{this}" 3978 3979 def toarray_sql(self, expression: exp.ToArray) -> str: 3980 arg = expression.this 3981 if not arg.type: 3982 from sqlglot.optimizer.annotate_types import annotate_types 3983 3984 arg = annotate_types(arg) 3985 3986 if arg.is_type(exp.DataType.Type.ARRAY): 3987 return self.sql(arg) 3988 3989 cond_for_null = arg.is_(exp.null()) 3990 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3991 3992 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3993 this = expression.this 3994 time_format = self.format_time(expression) 3995 3996 if time_format: 3997 return self.sql( 3998 exp.cast( 3999 exp.StrToTime(this=this, format=expression.args["format"]), 4000 exp.DataType.Type.TIME, 4001 ) 4002 ) 4003 4004 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4005 return self.sql(this) 4006 4007 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4008 4009 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4010 this = expression.this 4011 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4012 return self.sql(this) 4013 4014 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4015 4016 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4017 this = expression.this 4018 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4019 return self.sql(this) 4020 4021 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4022 4023 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4024 this = expression.this 4025 time_format = self.format_time(expression) 4026 4027 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4028 return self.sql( 4029 exp.cast( 4030 exp.StrToTime(this=this, format=expression.args["format"]), 4031 exp.DataType.Type.DATE, 4032 ) 4033 ) 4034 4035 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4036 return self.sql(this) 4037 4038 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4039 4040 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4041 return self.sql( 4042 exp.func( 4043 "DATEDIFF", 4044 expression.this, 4045 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4046 "day", 4047 ) 4048 ) 4049 4050 def lastday_sql(self, expression: exp.LastDay) -> str: 4051 if self.LAST_DAY_SUPPORTS_DATE_PART: 4052 return self.function_fallback_sql(expression) 4053 4054 unit = expression.text("unit") 4055 if unit and unit != "MONTH": 4056 self.unsupported("Date parts are not supported in LAST_DAY.") 4057 4058 return self.func("LAST_DAY", expression.this) 4059 4060 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4061 from sqlglot.dialects.dialect import unit_to_str 4062 4063 return self.func( 4064 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4065 ) 4066 4067 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4068 if self.CAN_IMPLEMENT_ARRAY_ANY: 4069 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4070 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4071 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4072 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4073 4074 from sqlglot.dialects import Dialect 4075 4076 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4077 if self.dialect.__class__ != Dialect: 4078 self.unsupported("ARRAY_ANY is unsupported") 4079 4080 return self.function_fallback_sql(expression) 4081 4082 def struct_sql(self, expression: exp.Struct) -> str: 4083 expression.set( 4084 "expressions", 4085 [ 4086 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4087 if isinstance(e, exp.PropertyEQ) 4088 else e 4089 for e in expression.expressions 4090 ], 4091 ) 4092 4093 return self.function_fallback_sql(expression) 4094 4095 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4096 low = self.sql(expression, "this") 4097 high = self.sql(expression, "expression") 4098 4099 return f"{low} TO {high}" 4100 4101 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4102 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4103 tables = f" {self.expressions(expression)}" 4104 4105 exists = " IF EXISTS" if expression.args.get("exists") else "" 4106 4107 on_cluster = self.sql(expression, "cluster") 4108 on_cluster = f" {on_cluster}" if on_cluster else "" 4109 4110 identity = self.sql(expression, "identity") 4111 identity = f" {identity} IDENTITY" if identity else "" 4112 4113 option = self.sql(expression, "option") 4114 option = f" {option}" if option else "" 4115 4116 partition = self.sql(expression, "partition") 4117 partition = f" {partition}" if partition else "" 4118 4119 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4120 4121 # This transpiles T-SQL's CONVERT function 4122 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4123 def convert_sql(self, expression: exp.Convert) -> str: 4124 to = expression.this 4125 value = expression.expression 4126 style = expression.args.get("style") 4127 safe = expression.args.get("safe") 4128 strict = expression.args.get("strict") 4129 4130 if not to or not value: 4131 return "" 4132 4133 # Retrieve length of datatype and override to default if not specified 4134 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4135 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4136 4137 transformed: t.Optional[exp.Expression] = None 4138 cast = exp.Cast if strict else exp.TryCast 4139 4140 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4141 if isinstance(style, exp.Literal) and style.is_int: 4142 from sqlglot.dialects.tsql import TSQL 4143 4144 style_value = style.name 4145 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4146 if not converted_style: 4147 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4148 4149 fmt = exp.Literal.string(converted_style) 4150 4151 if to.this == exp.DataType.Type.DATE: 4152 transformed = exp.StrToDate(this=value, format=fmt) 4153 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4154 transformed = exp.StrToTime(this=value, format=fmt) 4155 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4156 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4157 elif to.this == exp.DataType.Type.TEXT: 4158 transformed = exp.TimeToStr(this=value, format=fmt) 4159 4160 if not transformed: 4161 transformed = cast(this=value, to=to, safe=safe) 4162 4163 return self.sql(transformed) 4164 4165 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4166 this = expression.this 4167 if isinstance(this, exp.JSONPathWildcard): 4168 this = self.json_path_part(this) 4169 return f".{this}" if this else "" 4170 4171 if exp.SAFE_IDENTIFIER_RE.match(this): 4172 return f".{this}" 4173 4174 this = self.json_path_part(this) 4175 return ( 4176 f"[{this}]" 4177 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4178 else f".{this}" 4179 ) 4180 4181 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4182 this = self.json_path_part(expression.this) 4183 return f"[{this}]" if this else "" 4184 4185 def _simplify_unless_literal(self, expression: E) -> E: 4186 if not isinstance(expression, exp.Literal): 4187 from sqlglot.optimizer.simplify import simplify 4188 4189 expression = simplify(expression, dialect=self.dialect) 4190 4191 return expression 4192 4193 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4194 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4195 # The first modifier here will be the one closest to the AggFunc's arg 4196 mods = sorted( 4197 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4198 key=lambda x: 0 4199 if isinstance(x, exp.HavingMax) 4200 else (1 if isinstance(x, exp.Order) else 2), 4201 ) 4202 4203 if mods: 4204 mod = mods[0] 4205 this = expression.__class__(this=mod.this.copy()) 4206 this.meta["inline"] = True 4207 mod.this.replace(this) 4208 return self.sql(expression.this) 4209 4210 agg_func = expression.find(exp.AggFunc) 4211 4212 if agg_func: 4213 return self.sql(agg_func)[:-1] + f" {text})" 4214 4215 return f"{self.sql(expression, 'this')} {text}" 4216 4217 def _replace_line_breaks(self, string: str) -> str: 4218 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4219 if self.pretty: 4220 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4221 return string 4222 4223 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4224 option = self.sql(expression, "this") 4225 4226 if expression.expressions: 4227 upper = option.upper() 4228 4229 # Snowflake FILE_FORMAT options are separated by whitespace 4230 sep = " " if upper == "FILE_FORMAT" else ", " 4231 4232 # Databricks copy/format options do not set their list of values with EQ 4233 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4234 values = self.expressions(expression, flat=True, sep=sep) 4235 return f"{option}{op}({values})" 4236 4237 value = self.sql(expression, "expression") 4238 4239 if not value: 4240 return option 4241 4242 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4243 4244 return f"{option}{op}{value}" 4245 4246 def credentials_sql(self, expression: exp.Credentials) -> str: 4247 cred_expr = expression.args.get("credentials") 4248 if isinstance(cred_expr, exp.Literal): 4249 # Redshift case: CREDENTIALS <string> 4250 credentials = self.sql(expression, "credentials") 4251 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4252 else: 4253 # Snowflake case: CREDENTIALS = (...) 4254 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4255 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4256 4257 storage = self.sql(expression, "storage") 4258 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4259 4260 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4261 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4262 4263 iam_role = self.sql(expression, "iam_role") 4264 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4265 4266 region = self.sql(expression, "region") 4267 region = f" REGION {region}" if region else "" 4268 4269 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4270 4271 def copy_sql(self, expression: exp.Copy) -> str: 4272 this = self.sql(expression, "this") 4273 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4274 4275 credentials = self.sql(expression, "credentials") 4276 credentials = self.seg(credentials) if credentials else "" 4277 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4278 files = self.expressions(expression, key="files", flat=True) 4279 4280 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4281 params = self.expressions( 4282 expression, 4283 key="params", 4284 sep=sep, 4285 new_line=True, 4286 skip_last=True, 4287 skip_first=True, 4288 indent=self.COPY_PARAMS_ARE_WRAPPED, 4289 ) 4290 4291 if params: 4292 if self.COPY_PARAMS_ARE_WRAPPED: 4293 params = f" WITH ({params})" 4294 elif not self.pretty: 4295 params = f" {params}" 4296 4297 return f"COPY{this}{kind} {files}{credentials}{params}" 4298 4299 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4300 return "" 4301 4302 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4303 on_sql = "ON" if expression.args.get("on") else "OFF" 4304 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4305 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4306 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4307 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4308 4309 if filter_col or retention_period: 4310 on_sql = self.func("ON", filter_col, retention_period) 4311 4312 return f"DATA_DELETION={on_sql}" 4313 4314 def maskingpolicycolumnconstraint_sql( 4315 self, expression: exp.MaskingPolicyColumnConstraint 4316 ) -> str: 4317 this = self.sql(expression, "this") 4318 expressions = self.expressions(expression, flat=True) 4319 expressions = f" USING ({expressions})" if expressions else "" 4320 return f"MASKING POLICY {this}{expressions}" 4321 4322 def gapfill_sql(self, expression: exp.GapFill) -> str: 4323 this = self.sql(expression, "this") 4324 this = f"TABLE {this}" 4325 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4326 4327 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4328 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4329 4330 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4331 this = self.sql(expression, "this") 4332 expr = expression.expression 4333 4334 if isinstance(expr, exp.Func): 4335 # T-SQL's CLR functions are case sensitive 4336 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4337 else: 4338 expr = self.sql(expression, "expression") 4339 4340 return self.scope_resolution(expr, this) 4341 4342 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4343 if self.PARSE_JSON_NAME is None: 4344 return self.sql(expression.this) 4345 4346 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4347 4348 def rand_sql(self, expression: exp.Rand) -> str: 4349 lower = self.sql(expression, "lower") 4350 upper = self.sql(expression, "upper") 4351 4352 if lower and upper: 4353 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4354 return self.func("RAND", expression.this) 4355 4356 def changes_sql(self, expression: exp.Changes) -> str: 4357 information = self.sql(expression, "information") 4358 information = f"INFORMATION => {information}" 4359 at_before = self.sql(expression, "at_before") 4360 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4361 end = self.sql(expression, "end") 4362 end = f"{self.seg('')}{end}" if end else "" 4363 4364 return f"CHANGES ({information}){at_before}{end}" 4365 4366 def pad_sql(self, expression: exp.Pad) -> str: 4367 prefix = "L" if expression.args.get("is_left") else "R" 4368 4369 fill_pattern = self.sql(expression, "fill_pattern") or None 4370 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4371 fill_pattern = "' '" 4372 4373 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4374 4375 def summarize_sql(self, expression: exp.Summarize) -> str: 4376 table = " TABLE" if expression.args.get("table") else "" 4377 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4378 4379 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4380 generate_series = exp.GenerateSeries(**expression.args) 4381 4382 parent = expression.parent 4383 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4384 parent = parent.parent 4385 4386 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4387 return self.sql(exp.Unnest(expressions=[generate_series])) 4388 4389 if isinstance(parent, exp.Select): 4390 self.unsupported("GenerateSeries projection unnesting is not supported.") 4391 4392 return self.sql(generate_series) 4393 4394 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4395 exprs = expression.expressions 4396 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4397 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4398 else: 4399 rhs = self.expressions(expression) 4400 4401 return self.func(name, expression.this, rhs or None) 4402 4403 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4404 if self.SUPPORTS_CONVERT_TIMEZONE: 4405 return self.function_fallback_sql(expression) 4406 4407 source_tz = expression.args.get("source_tz") 4408 target_tz = expression.args.get("target_tz") 4409 timestamp = expression.args.get("timestamp") 4410 4411 if source_tz and timestamp: 4412 timestamp = exp.AtTimeZone( 4413 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4414 ) 4415 4416 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4417 4418 return self.sql(expr) 4419 4420 def json_sql(self, expression: exp.JSON) -> str: 4421 this = self.sql(expression, "this") 4422 this = f" {this}" if this else "" 4423 4424 _with = expression.args.get("with") 4425 4426 if _with is None: 4427 with_sql = "" 4428 elif not _with: 4429 with_sql = " WITHOUT" 4430 else: 4431 with_sql = " WITH" 4432 4433 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4434 4435 return f"JSON{this}{with_sql}{unique_sql}" 4436 4437 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4438 def _generate_on_options(arg: t.Any) -> str: 4439 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4440 4441 path = self.sql(expression, "path") 4442 returning = self.sql(expression, "returning") 4443 returning = f" RETURNING {returning}" if returning else "" 4444 4445 on_condition = self.sql(expression, "on_condition") 4446 on_condition = f" {on_condition}" if on_condition else "" 4447 4448 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4449 4450 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4451 else_ = "ELSE " if expression.args.get("else_") else "" 4452 condition = self.sql(expression, "expression") 4453 condition = f"WHEN {condition} THEN " if condition else else_ 4454 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4455 return f"{condition}{insert}" 4456 4457 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4458 kind = self.sql(expression, "kind") 4459 expressions = self.seg(self.expressions(expression, sep=" ")) 4460 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4461 return res 4462 4463 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4464 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4465 empty = expression.args.get("empty") 4466 empty = ( 4467 f"DEFAULT {empty} ON EMPTY" 4468 if isinstance(empty, exp.Expression) 4469 else self.sql(expression, "empty") 4470 ) 4471 4472 error = expression.args.get("error") 4473 error = ( 4474 f"DEFAULT {error} ON ERROR" 4475 if isinstance(error, exp.Expression) 4476 else self.sql(expression, "error") 4477 ) 4478 4479 if error and empty: 4480 error = ( 4481 f"{empty} {error}" 4482 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4483 else f"{error} {empty}" 4484 ) 4485 empty = "" 4486 4487 null = self.sql(expression, "null") 4488 4489 return f"{empty}{error}{null}" 4490 4491 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4492 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4493 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4494 4495 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4496 this = self.sql(expression, "this") 4497 path = self.sql(expression, "path") 4498 4499 passing = self.expressions(expression, "passing") 4500 passing = f" PASSING {passing}" if passing else "" 4501 4502 on_condition = self.sql(expression, "on_condition") 4503 on_condition = f" {on_condition}" if on_condition else "" 4504 4505 path = f"{path}{passing}{on_condition}" 4506 4507 return self.func("JSON_EXISTS", this, path) 4508 4509 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4510 array_agg = self.function_fallback_sql(expression) 4511 4512 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4513 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4514 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4515 parent = expression.parent 4516 if isinstance(parent, exp.Filter): 4517 parent_cond = parent.expression.this 4518 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4519 else: 4520 this = expression.this 4521 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4522 if this.find(exp.Column): 4523 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4524 this_sql = ( 4525 self.expressions(this) 4526 if isinstance(this, exp.Distinct) 4527 else self.sql(expression, "this") 4528 ) 4529 4530 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4531 4532 return array_agg 4533 4534 def apply_sql(self, expression: exp.Apply) -> str: 4535 this = self.sql(expression, "this") 4536 expr = self.sql(expression, "expression") 4537 4538 return f"{this} APPLY({expr})" 4539 4540 def grant_sql(self, expression: exp.Grant) -> str: 4541 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4542 4543 kind = self.sql(expression, "kind") 4544 kind = f" {kind}" if kind else "" 4545 4546 securable = self.sql(expression, "securable") 4547 securable = f" {securable}" if securable else "" 4548 4549 principals = self.expressions(expression, key="principals", flat=True) 4550 4551 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4552 4553 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4554 4555 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4556 this = self.sql(expression, "this") 4557 columns = self.expressions(expression, flat=True) 4558 columns = f"({columns})" if columns else "" 4559 4560 return f"{this}{columns}" 4561 4562 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4563 this = self.sql(expression, "this") 4564 4565 kind = self.sql(expression, "kind") 4566 kind = f"{kind} " if kind else "" 4567 4568 return f"{kind}{this}" 4569 4570 def columns_sql(self, expression: exp.Columns): 4571 func = self.function_fallback_sql(expression) 4572 if expression.args.get("unpack"): 4573 func = f"*{func}" 4574 4575 return func 4576 4577 def overlay_sql(self, expression: exp.Overlay): 4578 this = self.sql(expression, "this") 4579 expr = self.sql(expression, "expression") 4580 from_sql = self.sql(expression, "from") 4581 for_sql = self.sql(expression, "for") 4582 for_sql = f" FOR {for_sql}" if for_sql else "" 4583 4584 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4585 4586 @unsupported_args("format") 4587 def todouble_sql(self, expression: exp.ToDouble) -> str: 4588 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4589 4590 def string_sql(self, expression: exp.String) -> str: 4591 this = expression.this 4592 zone = expression.args.get("zone") 4593 4594 if zone: 4595 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4596 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4597 # set for source_tz to transpile the time conversion before the STRING cast 4598 this = exp.ConvertTimezone( 4599 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4600 ) 4601 4602 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4603 4604 def median_sql(self, expression: exp.Median): 4605 if not self.SUPPORTS_MEDIAN: 4606 return self.sql( 4607 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4608 ) 4609 4610 return self.function_fallback_sql(expression) 4611 4612 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4613 filler = self.sql(expression, "this") 4614 filler = f" {filler}" if filler else "" 4615 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4616 return f"TRUNCATE{filler} {with_count}" 4617 4618 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4619 if self.SUPPORTS_UNIX_SECONDS: 4620 return self.function_fallback_sql(expression) 4621 4622 start_ts = exp.cast( 4623 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4624 ) 4625 4626 return self.sql( 4627 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4628 ) 4629 4630 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4631 dim = expression.expression 4632 4633 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4634 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4635 if not (dim.is_int and dim.name == "1"): 4636 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4637 dim = None 4638 4639 # If dimension is required but not specified, default initialize it 4640 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4641 dim = exp.Literal.number(1) 4642 4643 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4644 4645 def attach_sql(self, expression: exp.Attach) -> str: 4646 this = self.sql(expression, "this") 4647 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4648 expressions = self.expressions(expression) 4649 expressions = f" ({expressions})" if expressions else "" 4650 4651 return f"ATTACH{exists_sql} {this}{expressions}" 4652 4653 def detach_sql(self, expression: exp.Detach) -> str: 4654 this = self.sql(expression, "this") 4655 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4656 4657 return f"DETACH{exists_sql} {this}" 4658 4659 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4660 this = self.sql(expression, "this") 4661 value = self.sql(expression, "expression") 4662 value = f" {value}" if value else "" 4663 return f"{this}{value}" 4664 4665 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4666 this_sql = self.sql(expression, "this") 4667 if isinstance(expression.this, exp.Table): 4668 this_sql = f"TABLE {this_sql}" 4669 4670 return self.func( 4671 "FEATURES_AT_TIME", 4672 this_sql, 4673 expression.args.get("time"), 4674 expression.args.get("num_rows"), 4675 expression.args.get("ignore_feature_nulls"), 4676 ) 4677 4678 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4679 return ( 4680 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4681 ) 4682 4683 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4684 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4685 encode = f"{encode} {self.sql(expression, 'this')}" 4686 4687 properties = expression.args.get("properties") 4688 if properties: 4689 encode = f"{encode} {self.properties(properties)}" 4690 4691 return encode 4692 4693 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4694 this = self.sql(expression, "this") 4695 include = f"INCLUDE {this}" 4696 4697 column_def = self.sql(expression, "column_def") 4698 if column_def: 4699 include = f"{include} {column_def}" 4700 4701 alias = self.sql(expression, "alias") 4702 if alias: 4703 include = f"{include} AS {alias}" 4704 4705 return include 4706 4707 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4708 name = f"NAME {self.sql(expression, 'this')}" 4709 return self.func("XMLELEMENT", name, *expression.expressions) 4710 4711 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4712 partitions = self.expressions(expression, "partition_expressions") 4713 create = self.expressions(expression, "create_expressions") 4714 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4715 4716 def partitionbyrangepropertydynamic_sql( 4717 self, expression: exp.PartitionByRangePropertyDynamic 4718 ) -> str: 4719 start = self.sql(expression, "start") 4720 end = self.sql(expression, "end") 4721 4722 every = expression.args["every"] 4723 if isinstance(every, exp.Interval) and every.this.is_string: 4724 every.this.replace(exp.Literal.number(every.name)) 4725 4726 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4727 4728 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4729 name = self.sql(expression, "this") 4730 values = self.expressions(expression, flat=True) 4731 4732 return f"NAME {name} VALUE {values}" 4733 4734 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4735 kind = self.sql(expression, "kind") 4736 sample = self.sql(expression, "sample") 4737 return f"SAMPLE {sample} {kind}" 4738 4739 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4740 kind = self.sql(expression, "kind") 4741 option = self.sql(expression, "option") 4742 option = f" {option}" if option else "" 4743 this = self.sql(expression, "this") 4744 this = f" {this}" if this else "" 4745 columns = self.expressions(expression) 4746 columns = f" {columns}" if columns else "" 4747 return f"{kind}{option} STATISTICS{this}{columns}" 4748 4749 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4750 this = self.sql(expression, "this") 4751 columns = self.expressions(expression) 4752 inner_expression = self.sql(expression, "expression") 4753 inner_expression = f" {inner_expression}" if inner_expression else "" 4754 update_options = self.sql(expression, "update_options") 4755 update_options = f" {update_options} UPDATE" if update_options else "" 4756 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4757 4758 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4759 kind = self.sql(expression, "kind") 4760 kind = f" {kind}" if kind else "" 4761 return f"DELETE{kind} STATISTICS" 4762 4763 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4764 inner_expression = self.sql(expression, "expression") 4765 return f"LIST CHAINED ROWS{inner_expression}" 4766 4767 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4768 kind = self.sql(expression, "kind") 4769 this = self.sql(expression, "this") 4770 this = f" {this}" if this else "" 4771 inner_expression = self.sql(expression, "expression") 4772 return f"VALIDATE {kind}{this}{inner_expression}" 4773 4774 def analyze_sql(self, expression: exp.Analyze) -> str: 4775 options = self.expressions(expression, key="options", sep=" ") 4776 options = f" {options}" if options else "" 4777 kind = self.sql(expression, "kind") 4778 kind = f" {kind}" if kind else "" 4779 this = self.sql(expression, "this") 4780 this = f" {this}" if this else "" 4781 mode = self.sql(expression, "mode") 4782 mode = f" {mode}" if mode else "" 4783 properties = self.sql(expression, "properties") 4784 properties = f" {properties}" if properties else "" 4785 partition = self.sql(expression, "partition") 4786 partition = f" {partition}" if partition else "" 4787 inner_expression = self.sql(expression, "expression") 4788 inner_expression = f" {inner_expression}" if inner_expression else "" 4789 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4790 4791 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4792 this = self.sql(expression, "this") 4793 namespaces = self.expressions(expression, key="namespaces") 4794 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4795 passing = self.expressions(expression, key="passing") 4796 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4797 columns = self.expressions(expression, key="columns") 4798 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4799 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4800 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4801 4802 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4803 this = self.sql(expression, "this") 4804 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4805 4806 def export_sql(self, expression: exp.Export) -> str: 4807 this = self.sql(expression, "this") 4808 connection = self.sql(expression, "connection") 4809 connection = f"WITH CONNECTION {connection} " if connection else "" 4810 options = self.sql(expression, "options") 4811 return f"EXPORT DATA {connection}{options} AS {this}" 4812 4813 def declare_sql(self, expression: exp.Declare) -> str: 4814 return f"DECLARE {self.expressions(expression, flat=True)}" 4815 4816 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4817 variable = self.sql(expression, "this") 4818 default = self.sql(expression, "default") 4819 default = f" = {default}" if default else "" 4820 4821 kind = self.sql(expression, "kind") 4822 if isinstance(expression.args.get("kind"), exp.Schema): 4823 kind = f"TABLE {kind}" 4824 4825 return f"{variable} AS {kind}{default}" 4826 4827 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4828 kind = self.sql(expression, "kind") 4829 this = self.sql(expression, "this") 4830 set = self.sql(expression, "expression") 4831 using = self.sql(expression, "using") 4832 using = f" USING {using}" if using else "" 4833 4834 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4835 4836 return f"{kind_sql} {this} SET {set}{using}" 4837 4838 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4839 params = self.expressions(expression, key="params", flat=True) 4840 return self.func(expression.name, *expression.expressions) + f"({params})" 4841 4842 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4843 return self.func(expression.name, *expression.expressions) 4844 4845 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4846 return self.anonymousaggfunc_sql(expression) 4847 4848 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4849 return self.parameterizedagg_sql(expression) 4850 4851 def show_sql(self, expression: exp.Show) -> str: 4852 self.unsupported("Unsupported SHOW statement") 4853 return "" 4854 4855 def put_sql(self, expression: exp.Put) -> str: 4856 props = expression.args.get("properties") 4857 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4858 this = self.sql(expression, "this") 4859 target = self.sql(expression, "target") 4860 return f"PUT {this} {target}{props_sql}"
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the
indentation of subqueries and filters under a
WHEREclause. Default: 2. - normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether to preserve comments in the output SQL code. Default: True
Generator( pretty: Optional[bool] = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: Union[str, bool, NoneType] = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None)
679 def __init__( 680 self, 681 pretty: t.Optional[bool] = None, 682 identify: str | bool = False, 683 normalize: bool = False, 684 pad: int = 2, 685 indent: int = 2, 686 normalize_functions: t.Optional[str | bool] = None, 687 unsupported_level: ErrorLevel = ErrorLevel.WARN, 688 max_unsupported: int = 3, 689 leading_comma: bool = False, 690 max_text_width: int = 80, 691 comments: bool = True, 692 dialect: DialectType = None, 693 ): 694 import sqlglot 695 from sqlglot.dialects import Dialect 696 697 self.pretty = pretty if pretty is not None else sqlglot.pretty 698 self.identify = identify 699 self.normalize = normalize 700 self.pad = pad 701 self._indent = indent 702 self.unsupported_level = unsupported_level 703 self.max_unsupported = max_unsupported 704 self.leading_comma = leading_comma 705 self.max_text_width = max_text_width 706 self.comments = comments 707 self.dialect = Dialect.get_or_raise(dialect) 708 709 # This is both a Dialect property and a Generator argument, so we prioritize the latter 710 self.normalize_functions = ( 711 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 712 ) 713 714 self.unsupported_messages: t.List[str] = [] 715 self._escaped_quote_end: str = ( 716 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 717 ) 718 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 719 720 self._next_name = name_sequence("_t") 721 722 self._identifier_start = self.dialect.IDENTIFIER_START 723 self._identifier_end = self.dialect.IDENTIFIER_END 724 725 self._quote_json_path_key_using_brackets = True
TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] =
{<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>}
TYPE_MAPPING =
{<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS =
{'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS =
{'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES =
{<Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
727 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 728 """ 729 Generates the SQL string corresponding to the given syntax tree. 730 731 Args: 732 expression: The syntax tree. 733 copy: Whether to copy the expression. The generator performs mutations so 734 it is safer to copy. 735 736 Returns: 737 The SQL string corresponding to `expression`. 738 """ 739 if copy: 740 expression = expression.copy() 741 742 expression = self.preprocess(expression) 743 744 self.unsupported_messages = [] 745 sql = self.sql(expression).strip() 746 747 if self.pretty: 748 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 749 750 if self.unsupported_level == ErrorLevel.IGNORE: 751 return sql 752 753 if self.unsupported_level == ErrorLevel.WARN: 754 for msg in self.unsupported_messages: 755 logger.warning(msg) 756 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 757 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 758 759 return sql
Generates the SQL string corresponding to the given syntax tree.
Arguments:
- expression: The syntax tree.
- copy: Whether to copy the expression. The generator performs mutations so it is safer to copy.
Returns:
The SQL string corresponding to
expression.
def
preprocess( self, expression: sqlglot.expressions.Expression) -> sqlglot.expressions.Expression:
761 def preprocess(self, expression: exp.Expression) -> exp.Expression: 762 """Apply generic preprocessing transformations to a given expression.""" 763 expression = self._move_ctes_to_top_level(expression) 764 765 if self.ENSURE_BOOLS: 766 from sqlglot.transforms import ensure_bools 767 768 expression = ensure_bools(expression) 769 770 return expression
Apply generic preprocessing transformations to a given expression.
def
maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None, separated: bool = False) -> str:
799 def maybe_comment( 800 self, 801 sql: str, 802 expression: t.Optional[exp.Expression] = None, 803 comments: t.Optional[t.List[str]] = None, 804 separated: bool = False, 805 ) -> str: 806 comments = ( 807 ((expression and expression.comments) if comments is None else comments) # type: ignore 808 if self.comments 809 else None 810 ) 811 812 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 813 return sql 814 815 comments_sql = " ".join( 816 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 817 ) 818 819 if not comments_sql: 820 return sql 821 822 comments_sql = self._replace_line_breaks(comments_sql) 823 824 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 825 return ( 826 f"{self.sep()}{comments_sql}{sql}" 827 if not sql or sql[0].isspace() 828 else f"{comments_sql}{self.sep()}{sql}" 829 ) 830 831 return f"{sql} {comments_sql}"
833 def wrap(self, expression: exp.Expression | str) -> str: 834 this_sql = ( 835 self.sql(expression) 836 if isinstance(expression, exp.UNWRAPPED_QUERIES) 837 else self.sql(expression, "this") 838 ) 839 if not this_sql: 840 return "()" 841 842 this_sql = self.indent(this_sql, level=1, pad=0) 843 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
def
indent( self, sql: str, level: int = 0, pad: Optional[int] = None, skip_first: bool = False, skip_last: bool = False) -> str:
859 def indent( 860 self, 861 sql: str, 862 level: int = 0, 863 pad: t.Optional[int] = None, 864 skip_first: bool = False, 865 skip_last: bool = False, 866 ) -> str: 867 if not self.pretty or not sql: 868 return sql 869 870 pad = self.pad if pad is None else pad 871 lines = sql.split("\n") 872 873 return "\n".join( 874 ( 875 line 876 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 877 else f"{' ' * (level * self._indent + pad)}{line}" 878 ) 879 for i, line in enumerate(lines) 880 )
def
sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
882 def sql( 883 self, 884 expression: t.Optional[str | exp.Expression], 885 key: t.Optional[str] = None, 886 comment: bool = True, 887 ) -> str: 888 if not expression: 889 return "" 890 891 if isinstance(expression, str): 892 return expression 893 894 if key: 895 value = expression.args.get(key) 896 if value: 897 return self.sql(value) 898 return "" 899 900 transform = self.TRANSFORMS.get(expression.__class__) 901 902 if callable(transform): 903 sql = transform(self, expression) 904 elif isinstance(expression, exp.Expression): 905 exp_handler_name = f"{expression.key}_sql" 906 907 if hasattr(self, exp_handler_name): 908 sql = getattr(self, exp_handler_name)(expression) 909 elif isinstance(expression, exp.Func): 910 sql = self.function_fallback_sql(expression) 911 elif isinstance(expression, exp.Property): 912 sql = self.property_sql(expression) 913 else: 914 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 915 else: 916 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 917 918 return self.maybe_comment(sql, expression) if self.comments and comment else sql
925 def cache_sql(self, expression: exp.Cache) -> str: 926 lazy = " LAZY" if expression.args.get("lazy") else "" 927 table = self.sql(expression, "this") 928 options = expression.args.get("options") 929 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 930 sql = self.sql(expression, "expression") 931 sql = f" AS{self.sep()}{sql}" if sql else "" 932 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 933 return self.prepend_ctes(expression, sql)
935 def characterset_sql(self, expression: exp.CharacterSet) -> str: 936 if isinstance(expression.parent, exp.Cast): 937 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 938 default = "DEFAULT " if expression.args.get("default") else "" 939 return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
953 def column_sql(self, expression: exp.Column) -> str: 954 join_mark = " (+)" if expression.args.get("join_mark") else "" 955 956 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 957 join_mark = "" 958 self.unsupported("Outer join syntax using the (+) operator is not supported.") 959 960 return f"{self.column_parts(expression)}{join_mark}"
968 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 969 column = self.sql(expression, "this") 970 kind = self.sql(expression, "kind") 971 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 972 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 973 kind = f"{sep}{kind}" if kind else "" 974 constraints = f" {constraints}" if constraints else "" 975 position = self.sql(expression, "position") 976 position = f" {position}" if position else "" 977 978 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 979 kind = "" 980 981 return f"{exists}{column}{kind}{constraints}{position}"
def
computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
988 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 989 this = self.sql(expression, "this") 990 if expression.args.get("not_null"): 991 persisted = " PERSISTED NOT NULL" 992 elif expression.args.get("persisted"): 993 persisted = " PERSISTED" 994 else: 995 persisted = "" 996 return f"AS {this}{persisted}"
def
compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1009 def generatedasidentitycolumnconstraint_sql( 1010 self, expression: exp.GeneratedAsIdentityColumnConstraint 1011 ) -> str: 1012 this = "" 1013 if expression.this is not None: 1014 on_null = " ON NULL" if expression.args.get("on_null") else "" 1015 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1016 1017 start = expression.args.get("start") 1018 start = f"START WITH {start}" if start else "" 1019 increment = expression.args.get("increment") 1020 increment = f" INCREMENT BY {increment}" if increment else "" 1021 minvalue = expression.args.get("minvalue") 1022 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1023 maxvalue = expression.args.get("maxvalue") 1024 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1025 cycle = expression.args.get("cycle") 1026 cycle_sql = "" 1027 1028 if cycle is not None: 1029 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1030 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1031 1032 sequence_opts = "" 1033 if start or increment or cycle_sql: 1034 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1035 sequence_opts = f" ({sequence_opts.strip()})" 1036 1037 expr = self.sql(expression, "expression") 1038 expr = f"({expr})" if expr else "IDENTITY" 1039 1040 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1042 def generatedasrowcolumnconstraint_sql( 1043 self, expression: exp.GeneratedAsRowColumnConstraint 1044 ) -> str: 1045 start = "START" if expression.args.get("start") else "END" 1046 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1047 return f"GENERATED ALWAYS AS ROW {start}{hidden}"
def
periodforsystemtimeconstraint_sql( self, expression: sqlglot.expressions.PeriodForSystemTimeConstraint) -> str:
def
notnullcolumnconstraint_sql(self, expression: sqlglot.expressions.NotNullColumnConstraint) -> str:
def
transformcolumnconstraint_sql(self, expression: sqlglot.expressions.TransformColumnConstraint) -> str:
def
primarykeycolumnconstraint_sql(self, expression: sqlglot.expressions.PrimaryKeyColumnConstraint) -> str:
def
uniquecolumnconstraint_sql(self, expression: sqlglot.expressions.UniqueColumnConstraint) -> str:
1066 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1067 this = self.sql(expression, "this") 1068 this = f" {this}" if this else "" 1069 index_type = expression.args.get("index_type") 1070 index_type = f" USING {index_type}" if index_type else "" 1071 on_conflict = self.sql(expression, "on_conflict") 1072 on_conflict = f" {on_conflict}" if on_conflict else "" 1073 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1074 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
1079 def create_sql(self, expression: exp.Create) -> str: 1080 kind = self.sql(expression, "kind") 1081 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1082 properties = expression.args.get("properties") 1083 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1084 1085 this = self.createable_sql(expression, properties_locs) 1086 1087 properties_sql = "" 1088 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1089 exp.Properties.Location.POST_WITH 1090 ): 1091 properties_sql = self.sql( 1092 exp.Properties( 1093 expressions=[ 1094 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1095 *properties_locs[exp.Properties.Location.POST_WITH], 1096 ] 1097 ) 1098 ) 1099 1100 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1101 properties_sql = self.sep() + properties_sql 1102 elif not self.pretty: 1103 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1104 properties_sql = f" {properties_sql}" 1105 1106 begin = " BEGIN" if expression.args.get("begin") else "" 1107 end = " END" if expression.args.get("end") else "" 1108 1109 expression_sql = self.sql(expression, "expression") 1110 if expression_sql: 1111 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1112 1113 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1114 postalias_props_sql = "" 1115 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1116 postalias_props_sql = self.properties( 1117 exp.Properties( 1118 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1119 ), 1120 wrapped=False, 1121 ) 1122 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1123 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1124 1125 postindex_props_sql = "" 1126 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1127 postindex_props_sql = self.properties( 1128 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1129 wrapped=False, 1130 prefix=" ", 1131 ) 1132 1133 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1134 indexes = f" {indexes}" if indexes else "" 1135 index_sql = indexes + postindex_props_sql 1136 1137 replace = " OR REPLACE" if expression.args.get("replace") else "" 1138 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1139 unique = " UNIQUE" if expression.args.get("unique") else "" 1140 1141 clustered = expression.args.get("clustered") 1142 if clustered is None: 1143 clustered_sql = "" 1144 elif clustered: 1145 clustered_sql = " CLUSTERED COLUMNSTORE" 1146 else: 1147 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1148 1149 postcreate_props_sql = "" 1150 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1151 postcreate_props_sql = self.properties( 1152 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1153 sep=" ", 1154 prefix=" ", 1155 wrapped=False, 1156 ) 1157 1158 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1159 1160 postexpression_props_sql = "" 1161 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1162 postexpression_props_sql = self.properties( 1163 exp.Properties( 1164 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1165 ), 1166 sep=" ", 1167 prefix=" ", 1168 wrapped=False, 1169 ) 1170 1171 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1172 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1173 no_schema_binding = ( 1174 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1175 ) 1176 1177 clone = self.sql(expression, "clone") 1178 clone = f" {clone}" if clone else "" 1179 1180 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1181 properties_expression = f"{expression_sql}{properties_sql}" 1182 else: 1183 properties_expression = f"{properties_sql}{expression_sql}" 1184 1185 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1186 return self.prepend_ctes(expression, expression_sql)
1188 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1189 start = self.sql(expression, "start") 1190 start = f"START WITH {start}" if start else "" 1191 increment = self.sql(expression, "increment") 1192 increment = f" INCREMENT BY {increment}" if increment else "" 1193 minvalue = self.sql(expression, "minvalue") 1194 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1195 maxvalue = self.sql(expression, "maxvalue") 1196 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1197 owned = self.sql(expression, "owned") 1198 owned = f" OWNED BY {owned}" if owned else "" 1199 1200 cache = expression.args.get("cache") 1201 if cache is None: 1202 cache_str = "" 1203 elif cache is True: 1204 cache_str = " CACHE" 1205 else: 1206 cache_str = f" CACHE {cache}" 1207 1208 options = self.expressions(expression, key="options", flat=True, sep=" ") 1209 options = f" {options}" if options else "" 1210 1211 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1213 def clone_sql(self, expression: exp.Clone) -> str: 1214 this = self.sql(expression, "this") 1215 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1216 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1217 return f"{shallow}{keyword} {this}"
1219 def describe_sql(self, expression: exp.Describe) -> str: 1220 style = expression.args.get("style") 1221 style = f" {style}" if style else "" 1222 partition = self.sql(expression, "partition") 1223 partition = f" {partition}" if partition else "" 1224 format = self.sql(expression, "format") 1225 format = f" {format}" if format else "" 1226 1227 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1239 def with_sql(self, expression: exp.With) -> str: 1240 sql = self.expressions(expression, flat=True) 1241 recursive = ( 1242 "RECURSIVE " 1243 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1244 else "" 1245 ) 1246 search = self.sql(expression, "search") 1247 search = f" {search}" if search else "" 1248 1249 return f"WITH {recursive}{sql}{search}"
1251 def cte_sql(self, expression: exp.CTE) -> str: 1252 alias = expression.args.get("alias") 1253 if alias: 1254 alias.add_comments(expression.pop_comments()) 1255 1256 alias_sql = self.sql(expression, "alias") 1257 1258 materialized = expression.args.get("materialized") 1259 if materialized is False: 1260 materialized = "NOT MATERIALIZED " 1261 elif materialized: 1262 materialized = "MATERIALIZED " 1263 1264 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1266 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1267 alias = self.sql(expression, "this") 1268 columns = self.expressions(expression, key="columns", flat=True) 1269 columns = f"({columns})" if columns else "" 1270 1271 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1272 columns = "" 1273 self.unsupported("Named columns are not supported in table alias.") 1274 1275 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1276 alias = self._next_name() 1277 1278 return f"{alias}{columns}"
def
hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str:
1286 def hexstring_sql( 1287 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1288 ) -> str: 1289 this = self.sql(expression, "this") 1290 is_integer_type = expression.args.get("is_integer") 1291 1292 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1293 not self.dialect.HEX_START and not binary_function_repr 1294 ): 1295 # Integer representation will be returned if: 1296 # - The read dialect treats the hex value as integer literal but not the write 1297 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1298 return f"{int(this, 16)}" 1299 1300 if not is_integer_type: 1301 # Read dialect treats the hex value as BINARY/BLOB 1302 if binary_function_repr: 1303 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1304 return self.func(binary_function_repr, exp.Literal.string(this)) 1305 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1306 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1307 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1308 1309 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1317 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1318 this = self.sql(expression, "this") 1319 escape = expression.args.get("escape") 1320 1321 if self.dialect.UNICODE_START: 1322 escape_substitute = r"\\\1" 1323 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1324 else: 1325 escape_substitute = r"\\u\1" 1326 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1327 1328 if escape: 1329 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1330 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1331 else: 1332 escape_pattern = ESCAPED_UNICODE_RE 1333 escape_sql = "" 1334 1335 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1336 this = escape_pattern.sub(escape_substitute, this) 1337 1338 return f"{left_quote}{this}{right_quote}{escape_sql}"
1350 def datatype_sql(self, expression: exp.DataType) -> str: 1351 nested = "" 1352 values = "" 1353 interior = self.expressions(expression, flat=True) 1354 1355 type_value = expression.this 1356 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1357 type_sql = self.sql(expression, "kind") 1358 else: 1359 type_sql = ( 1360 self.TYPE_MAPPING.get(type_value, type_value.value) 1361 if isinstance(type_value, exp.DataType.Type) 1362 else type_value 1363 ) 1364 1365 if interior: 1366 if expression.args.get("nested"): 1367 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1368 if expression.args.get("values") is not None: 1369 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1370 values = self.expressions(expression, key="values", flat=True) 1371 values = f"{delimiters[0]}{values}{delimiters[1]}" 1372 elif type_value == exp.DataType.Type.INTERVAL: 1373 nested = f" {interior}" 1374 else: 1375 nested = f"({interior})" 1376 1377 type_sql = f"{type_sql}{nested}{values}" 1378 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1379 exp.DataType.Type.TIMETZ, 1380 exp.DataType.Type.TIMESTAMPTZ, 1381 ): 1382 type_sql = f"{type_sql} WITH TIME ZONE" 1383 1384 return type_sql
1386 def directory_sql(self, expression: exp.Directory) -> str: 1387 local = "LOCAL " if expression.args.get("local") else "" 1388 row_format = self.sql(expression, "row_format") 1389 row_format = f" {row_format}" if row_format else "" 1390 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1392 def delete_sql(self, expression: exp.Delete) -> str: 1393 this = self.sql(expression, "this") 1394 this = f" FROM {this}" if this else "" 1395 using = self.sql(expression, "using") 1396 using = f" USING {using}" if using else "" 1397 cluster = self.sql(expression, "cluster") 1398 cluster = f" {cluster}" if cluster else "" 1399 where = self.sql(expression, "where") 1400 returning = self.sql(expression, "returning") 1401 limit = self.sql(expression, "limit") 1402 tables = self.expressions(expression, key="tables") 1403 tables = f" {tables}" if tables else "" 1404 if self.RETURNING_END: 1405 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1406 else: 1407 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1408 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1410 def drop_sql(self, expression: exp.Drop) -> str: 1411 this = self.sql(expression, "this") 1412 expressions = self.expressions(expression, flat=True) 1413 expressions = f" ({expressions})" if expressions else "" 1414 kind = expression.args["kind"] 1415 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1416 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1417 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1418 on_cluster = self.sql(expression, "cluster") 1419 on_cluster = f" {on_cluster}" if on_cluster else "" 1420 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1421 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1422 cascade = " CASCADE" if expression.args.get("cascade") else "" 1423 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1424 purge = " PURGE" if expression.args.get("purge") else "" 1425 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1427 def set_operation(self, expression: exp.SetOperation) -> str: 1428 op_type = type(expression) 1429 op_name = op_type.key.upper() 1430 1431 distinct = expression.args.get("distinct") 1432 if ( 1433 distinct is False 1434 and op_type in (exp.Except, exp.Intersect) 1435 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1436 ): 1437 self.unsupported(f"{op_name} ALL is not supported") 1438 1439 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1440 1441 if distinct is None: 1442 distinct = default_distinct 1443 if distinct is None: 1444 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1445 1446 if distinct is default_distinct: 1447 kind = "" 1448 else: 1449 kind = " DISTINCT" if distinct else " ALL" 1450 1451 by_name = " BY NAME" if expression.args.get("by_name") else "" 1452 return f"{op_name}{kind}{by_name}"
1454 def set_operations(self, expression: exp.SetOperation) -> str: 1455 if not self.SET_OP_MODIFIERS: 1456 limit = expression.args.get("limit") 1457 order = expression.args.get("order") 1458 1459 if limit or order: 1460 select = self._move_ctes_to_top_level( 1461 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1462 ) 1463 1464 if limit: 1465 select = select.limit(limit.pop(), copy=False) 1466 if order: 1467 select = select.order_by(order.pop(), copy=False) 1468 return self.sql(select) 1469 1470 sqls: t.List[str] = [] 1471 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1472 1473 while stack: 1474 node = stack.pop() 1475 1476 if isinstance(node, exp.SetOperation): 1477 stack.append(node.expression) 1478 stack.append( 1479 self.maybe_comment( 1480 self.set_operation(node), comments=node.comments, separated=True 1481 ) 1482 ) 1483 stack.append(node.this) 1484 else: 1485 sqls.append(self.sql(node)) 1486 1487 this = self.sep().join(sqls) 1488 this = self.query_modifiers(expression, this) 1489 return self.prepend_ctes(expression, this)
1491 def fetch_sql(self, expression: exp.Fetch) -> str: 1492 direction = expression.args.get("direction") 1493 direction = f" {direction}" if direction else "" 1494 count = self.sql(expression, "count") 1495 count = f" {count}" if count else "" 1496 limit_options = self.sql(expression, "limit_options") 1497 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1498 return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1500 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1501 percent = " PERCENT" if expression.args.get("percent") else "" 1502 rows = " ROWS" if expression.args.get("rows") else "" 1503 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1504 if not with_ties and rows: 1505 with_ties = " ONLY" 1506 return f"{percent}{rows}{with_ties}"
1508 def filter_sql(self, expression: exp.Filter) -> str: 1509 if self.AGGREGATE_FILTER_SUPPORTED: 1510 this = self.sql(expression, "this") 1511 where = self.sql(expression, "expression").strip() 1512 return f"{this} FILTER({where})" 1513 1514 agg = expression.this 1515 agg_arg = agg.this 1516 cond = expression.expression.this 1517 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1518 return self.sql(agg)
1527 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1528 using = self.sql(expression, "using") 1529 using = f" USING {using}" if using else "" 1530 columns = self.expressions(expression, key="columns", flat=True) 1531 columns = f"({columns})" if columns else "" 1532 partition_by = self.expressions(expression, key="partition_by", flat=True) 1533 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1534 where = self.sql(expression, "where") 1535 include = self.expressions(expression, key="include", flat=True) 1536 if include: 1537 include = f" INCLUDE ({include})" 1538 with_storage = self.expressions(expression, key="with_storage", flat=True) 1539 with_storage = f" WITH ({with_storage})" if with_storage else "" 1540 tablespace = self.sql(expression, "tablespace") 1541 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1542 on = self.sql(expression, "on") 1543 on = f" ON {on}" if on else "" 1544 1545 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1547 def index_sql(self, expression: exp.Index) -> str: 1548 unique = "UNIQUE " if expression.args.get("unique") else "" 1549 primary = "PRIMARY " if expression.args.get("primary") else "" 1550 amp = "AMP " if expression.args.get("amp") else "" 1551 name = self.sql(expression, "this") 1552 name = f"{name} " if name else "" 1553 table = self.sql(expression, "table") 1554 table = f"{self.INDEX_ON} {table}" if table else "" 1555 1556 index = "INDEX " if not table else "" 1557 1558 params = self.sql(expression, "params") 1559 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1561 def identifier_sql(self, expression: exp.Identifier) -> str: 1562 text = expression.name 1563 lower = text.lower() 1564 text = lower if self.normalize and not expression.quoted else text 1565 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1566 if ( 1567 expression.quoted 1568 or self.dialect.can_identify(text, self.identify) 1569 or lower in self.RESERVED_KEYWORDS 1570 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1571 ): 1572 text = f"{self._identifier_start}{text}{self._identifier_end}" 1573 return text
1588 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1589 input_format = self.sql(expression, "input_format") 1590 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1591 output_format = self.sql(expression, "output_format") 1592 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1593 return self.sep().join((input_format, output_format))
1603 def properties_sql(self, expression: exp.Properties) -> str: 1604 root_properties = [] 1605 with_properties = [] 1606 1607 for p in expression.expressions: 1608 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1609 if p_loc == exp.Properties.Location.POST_WITH: 1610 with_properties.append(p) 1611 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1612 root_properties.append(p) 1613 1614 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1615 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1616 1617 if root_props and with_props and not self.pretty: 1618 with_props = " " + with_props 1619 1620 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1627 def properties( 1628 self, 1629 properties: exp.Properties, 1630 prefix: str = "", 1631 sep: str = ", ", 1632 suffix: str = "", 1633 wrapped: bool = True, 1634 ) -> str: 1635 if properties.expressions: 1636 expressions = self.expressions(properties, sep=sep, indent=False) 1637 if expressions: 1638 expressions = self.wrap(expressions) if wrapped else expressions 1639 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1640 return ""
1645 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1646 properties_locs = defaultdict(list) 1647 for p in properties.expressions: 1648 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1649 if p_loc != exp.Properties.Location.UNSUPPORTED: 1650 properties_locs[p_loc].append(p) 1651 else: 1652 self.unsupported(f"Unsupported property {p.key}") 1653 1654 return properties_locs
def
property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1661 def property_sql(self, expression: exp.Property) -> str: 1662 property_cls = expression.__class__ 1663 if property_cls == exp.Property: 1664 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1665 1666 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1667 if not property_name: 1668 self.unsupported(f"Unsupported property {expression.key}") 1669 1670 return f"{property_name}={self.sql(expression, 'this')}"
1672 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1673 if self.SUPPORTS_CREATE_TABLE_LIKE: 1674 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1675 options = f" {options}" if options else "" 1676 1677 like = f"LIKE {self.sql(expression, 'this')}{options}" 1678 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1679 like = f"({like})" 1680 1681 return like 1682 1683 if expression.expressions: 1684 self.unsupported("Transpilation of LIKE property options is unsupported") 1685 1686 select = exp.select("*").from_(expression.this).limit(0) 1687 return f"AS {self.sql(select)}"
1694 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1695 no = "NO " if expression.args.get("no") else "" 1696 local = expression.args.get("local") 1697 local = f"{local} " if local else "" 1698 dual = "DUAL " if expression.args.get("dual") else "" 1699 before = "BEFORE " if expression.args.get("before") else "" 1700 after = "AFTER " if expression.args.get("after") else "" 1701 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1717 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1718 if expression.args.get("no"): 1719 return "NO MERGEBLOCKRATIO" 1720 if expression.args.get("default"): 1721 return "DEFAULT MERGEBLOCKRATIO" 1722 1723 percent = " PERCENT" if expression.args.get("percent") else "" 1724 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1726 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1727 default = expression.args.get("default") 1728 minimum = expression.args.get("minimum") 1729 maximum = expression.args.get("maximum") 1730 if default or minimum or maximum: 1731 if default: 1732 prop = "DEFAULT" 1733 elif minimum: 1734 prop = "MINIMUM" 1735 else: 1736 prop = "MAXIMUM" 1737 return f"{prop} DATABLOCKSIZE" 1738 units = expression.args.get("units") 1739 units = f" {units}" if units else "" 1740 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1742 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1743 autotemp = expression.args.get("autotemp") 1744 always = expression.args.get("always") 1745 default = expression.args.get("default") 1746 manual = expression.args.get("manual") 1747 never = expression.args.get("never") 1748 1749 if autotemp is not None: 1750 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1751 elif always: 1752 prop = "ALWAYS" 1753 elif default: 1754 prop = "DEFAULT" 1755 elif manual: 1756 prop = "MANUAL" 1757 elif never: 1758 prop = "NEVER" 1759 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1761 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1762 no = expression.args.get("no") 1763 no = " NO" if no else "" 1764 concurrent = expression.args.get("concurrent") 1765 concurrent = " CONCURRENT" if concurrent else "" 1766 target = self.sql(expression, "target") 1767 target = f" {target}" if target else "" 1768 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1770 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1771 if isinstance(expression.this, list): 1772 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1773 if expression.this: 1774 modulus = self.sql(expression, "this") 1775 remainder = self.sql(expression, "expression") 1776 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1777 1778 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1779 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1780 return f"FROM ({from_expressions}) TO ({to_expressions})"
1782 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1783 this = self.sql(expression, "this") 1784 1785 for_values_or_default = expression.expression 1786 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1787 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1788 else: 1789 for_values_or_default = " DEFAULT" 1790 1791 return f"PARTITION OF {this}{for_values_or_default}"
1793 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1794 kind = expression.args.get("kind") 1795 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1796 for_or_in = expression.args.get("for_or_in") 1797 for_or_in = f" {for_or_in}" if for_or_in else "" 1798 lock_type = expression.args.get("lock_type") 1799 override = " OVERRIDE" if expression.args.get("override") else "" 1800 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1802 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1803 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1804 statistics = expression.args.get("statistics") 1805 statistics_sql = "" 1806 if statistics is not None: 1807 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1808 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1810 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1811 this = self.sql(expression, "this") 1812 this = f"HISTORY_TABLE={this}" if this else "" 1813 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1814 data_consistency = ( 1815 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1816 ) 1817 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1818 retention_period = ( 1819 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1820 ) 1821 1822 if this: 1823 on_sql = self.func("ON", this, data_consistency, retention_period) 1824 else: 1825 on_sql = "ON" if expression.args.get("on") else "OFF" 1826 1827 sql = f"SYSTEM_VERSIONING={on_sql}" 1828 1829 return f"WITH({sql})" if expression.args.get("with") else sql
1831 def insert_sql(self, expression: exp.Insert) -> str: 1832 hint = self.sql(expression, "hint") 1833 overwrite = expression.args.get("overwrite") 1834 1835 if isinstance(expression.this, exp.Directory): 1836 this = " OVERWRITE" if overwrite else " INTO" 1837 else: 1838 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1839 1840 stored = self.sql(expression, "stored") 1841 stored = f" {stored}" if stored else "" 1842 alternative = expression.args.get("alternative") 1843 alternative = f" OR {alternative}" if alternative else "" 1844 ignore = " IGNORE" if expression.args.get("ignore") else "" 1845 is_function = expression.args.get("is_function") 1846 if is_function: 1847 this = f"{this} FUNCTION" 1848 this = f"{this} {self.sql(expression, 'this')}" 1849 1850 exists = " IF EXISTS" if expression.args.get("exists") else "" 1851 where = self.sql(expression, "where") 1852 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1853 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1854 on_conflict = self.sql(expression, "conflict") 1855 on_conflict = f" {on_conflict}" if on_conflict else "" 1856 by_name = " BY NAME" if expression.args.get("by_name") else "" 1857 returning = self.sql(expression, "returning") 1858 1859 if self.RETURNING_END: 1860 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1861 else: 1862 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1863 1864 partition_by = self.sql(expression, "partition") 1865 partition_by = f" {partition_by}" if partition_by else "" 1866 settings = self.sql(expression, "settings") 1867 settings = f" {settings}" if settings else "" 1868 1869 source = self.sql(expression, "source") 1870 source = f"TABLE {source}" if source else "" 1871 1872 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1873 return self.prepend_ctes(expression, sql)
1891 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1892 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1893 1894 constraint = self.sql(expression, "constraint") 1895 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1896 1897 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1898 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1899 action = self.sql(expression, "action") 1900 1901 expressions = self.expressions(expression, flat=True) 1902 if expressions: 1903 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1904 expressions = f" {set_keyword}{expressions}" 1905 1906 where = self.sql(expression, "where") 1907 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def
rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1912 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1913 fields = self.sql(expression, "fields") 1914 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1915 escaped = self.sql(expression, "escaped") 1916 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1917 items = self.sql(expression, "collection_items") 1918 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1919 keys = self.sql(expression, "map_keys") 1920 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1921 lines = self.sql(expression, "lines") 1922 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1923 null = self.sql(expression, "null") 1924 null = f" NULL DEFINED AS {null}" if null else "" 1925 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1953 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1954 table = self.table_parts(expression) 1955 only = "ONLY " if expression.args.get("only") else "" 1956 partition = self.sql(expression, "partition") 1957 partition = f" {partition}" if partition else "" 1958 version = self.sql(expression, "version") 1959 version = f" {version}" if version else "" 1960 alias = self.sql(expression, "alias") 1961 alias = f"{sep}{alias}" if alias else "" 1962 1963 sample = self.sql(expression, "sample") 1964 if self.dialect.ALIAS_POST_TABLESAMPLE: 1965 sample_pre_alias = sample 1966 sample_post_alias = "" 1967 else: 1968 sample_pre_alias = "" 1969 sample_post_alias = sample 1970 1971 hints = self.expressions(expression, key="hints", sep=" ") 1972 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1973 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1974 joins = self.indent( 1975 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1976 ) 1977 laterals = self.expressions(expression, key="laterals", sep="") 1978 1979 file_format = self.sql(expression, "format") 1980 if file_format: 1981 pattern = self.sql(expression, "pattern") 1982 pattern = f", PATTERN => {pattern}" if pattern else "" 1983 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1984 1985 ordinality = expression.args.get("ordinality") or "" 1986 if ordinality: 1987 ordinality = f" WITH ORDINALITY{alias}" 1988 alias = "" 1989 1990 when = self.sql(expression, "when") 1991 if when: 1992 table = f"{table} {when}" 1993 1994 changes = self.sql(expression, "changes") 1995 changes = f" {changes}" if changes else "" 1996 1997 rows_from = self.expressions(expression, key="rows_from") 1998 if rows_from: 1999 table = f"ROWS FROM {self.wrap(rows_from)}" 2000 2001 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
def
tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
2003 def tablesample_sql( 2004 self, 2005 expression: exp.TableSample, 2006 tablesample_keyword: t.Optional[str] = None, 2007 ) -> str: 2008 method = self.sql(expression, "method") 2009 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2010 numerator = self.sql(expression, "bucket_numerator") 2011 denominator = self.sql(expression, "bucket_denominator") 2012 field = self.sql(expression, "bucket_field") 2013 field = f" ON {field}" if field else "" 2014 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2015 seed = self.sql(expression, "seed") 2016 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2017 2018 size = self.sql(expression, "size") 2019 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2020 size = f"{size} ROWS" 2021 2022 percent = self.sql(expression, "percent") 2023 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2024 percent = f"{percent} PERCENT" 2025 2026 expr = f"{bucket}{percent}{size}" 2027 if self.TABLESAMPLE_REQUIRES_PARENS: 2028 expr = f"({expr})" 2029 2030 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2032 def pivot_sql(self, expression: exp.Pivot) -> str: 2033 expressions = self.expressions(expression, flat=True) 2034 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2035 2036 if expression.this: 2037 this = self.sql(expression, "this") 2038 if not expressions: 2039 return f"UNPIVOT {this}" 2040 2041 on = f"{self.seg('ON')} {expressions}" 2042 into = self.sql(expression, "into") 2043 into = f"{self.seg('INTO')} {into}" if into else "" 2044 using = self.expressions(expression, key="using", flat=True) 2045 using = f"{self.seg('USING')} {using}" if using else "" 2046 group = self.sql(expression, "group") 2047 return f"{direction} {this}{on}{into}{using}{group}" 2048 2049 alias = self.sql(expression, "alias") 2050 alias = f" AS {alias}" if alias else "" 2051 2052 field = self.sql(expression, "field") 2053 2054 include_nulls = expression.args.get("include_nulls") 2055 if include_nulls is not None: 2056 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2057 else: 2058 nulls = "" 2059 2060 default_on_null = self.sql(expression, "default_on_null") 2061 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2062 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
2073 def update_sql(self, expression: exp.Update) -> str: 2074 this = self.sql(expression, "this") 2075 set_sql = self.expressions(expression, flat=True) 2076 from_sql = self.sql(expression, "from") 2077 where_sql = self.sql(expression, "where") 2078 returning = self.sql(expression, "returning") 2079 order = self.sql(expression, "order") 2080 limit = self.sql(expression, "limit") 2081 if self.RETURNING_END: 2082 expression_sql = f"{from_sql}{where_sql}{returning}" 2083 else: 2084 expression_sql = f"{returning}{from_sql}{where_sql}" 2085 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2086 return self.prepend_ctes(expression, sql)
2088 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2089 values_as_table = values_as_table and self.VALUES_AS_TABLE 2090 2091 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2092 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2093 args = self.expressions(expression) 2094 alias = self.sql(expression, "alias") 2095 values = f"VALUES{self.seg('')}{args}" 2096 values = ( 2097 f"({values})" 2098 if self.WRAP_DERIVED_VALUES 2099 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2100 else values 2101 ) 2102 return f"{values} AS {alias}" if alias else values 2103 2104 # Converts `VALUES...` expression into a series of select unions. 2105 alias_node = expression.args.get("alias") 2106 column_names = alias_node and alias_node.columns 2107 2108 selects: t.List[exp.Query] = [] 2109 2110 for i, tup in enumerate(expression.expressions): 2111 row = tup.expressions 2112 2113 if i == 0 and column_names: 2114 row = [ 2115 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2116 ] 2117 2118 selects.append(exp.Select(expressions=row)) 2119 2120 if self.pretty: 2121 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2122 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2123 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2124 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2125 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2126 2127 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2128 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2129 return f"({unions}){alias}"
2134 @unsupported_args("expressions") 2135 def into_sql(self, expression: exp.Into) -> str: 2136 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2137 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2138 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2155 def group_sql(self, expression: exp.Group) -> str: 2156 group_by_all = expression.args.get("all") 2157 if group_by_all is True: 2158 modifier = " ALL" 2159 elif group_by_all is False: 2160 modifier = " DISTINCT" 2161 else: 2162 modifier = "" 2163 2164 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2165 2166 grouping_sets = self.expressions(expression, key="grouping_sets") 2167 cube = self.expressions(expression, key="cube") 2168 rollup = self.expressions(expression, key="rollup") 2169 2170 groupings = csv( 2171 self.seg(grouping_sets) if grouping_sets else "", 2172 self.seg(cube) if cube else "", 2173 self.seg(rollup) if rollup else "", 2174 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2175 sep=self.GROUPINGS_SEP, 2176 ) 2177 2178 if ( 2179 expression.expressions 2180 and groupings 2181 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2182 ): 2183 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2184 2185 return f"{group_by}{groupings}"
2191 def connect_sql(self, expression: exp.Connect) -> str: 2192 start = self.sql(expression, "start") 2193 start = self.seg(f"START WITH {start}") if start else "" 2194 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2195 connect = self.sql(expression, "connect") 2196 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2197 return start + connect
2202 def join_sql(self, expression: exp.Join) -> str: 2203 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2204 side = None 2205 else: 2206 side = expression.side 2207 2208 op_sql = " ".join( 2209 op 2210 for op in ( 2211 expression.method, 2212 "GLOBAL" if expression.args.get("global") else None, 2213 side, 2214 expression.kind, 2215 expression.hint if self.JOIN_HINTS else None, 2216 ) 2217 if op 2218 ) 2219 match_cond = self.sql(expression, "match_condition") 2220 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2221 on_sql = self.sql(expression, "on") 2222 using = expression.args.get("using") 2223 2224 if not on_sql and using: 2225 on_sql = csv(*(self.sql(column) for column in using)) 2226 2227 this = expression.this 2228 this_sql = self.sql(this) 2229 2230 exprs = self.expressions(expression) 2231 if exprs: 2232 this_sql = f"{this_sql},{self.seg(exprs)}" 2233 2234 if on_sql: 2235 on_sql = self.indent(on_sql, skip_first=True) 2236 space = self.seg(" " * self.pad) if self.pretty else " " 2237 if using: 2238 on_sql = f"{space}USING ({on_sql})" 2239 else: 2240 on_sql = f"{space}ON {on_sql}" 2241 elif not op_sql: 2242 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2243 return f" {this_sql}" 2244 2245 return f", {this_sql}" 2246 2247 if op_sql != "STRAIGHT_JOIN": 2248 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2249 2250 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2257 def lateral_op(self, expression: exp.Lateral) -> str: 2258 cross_apply = expression.args.get("cross_apply") 2259 2260 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2261 if cross_apply is True: 2262 op = "INNER JOIN " 2263 elif cross_apply is False: 2264 op = "LEFT JOIN " 2265 else: 2266 op = "" 2267 2268 return f"{op}LATERAL"
2270 def lateral_sql(self, expression: exp.Lateral) -> str: 2271 this = self.sql(expression, "this") 2272 2273 if expression.args.get("view"): 2274 alias = expression.args["alias"] 2275 columns = self.expressions(alias, key="columns", flat=True) 2276 table = f" {alias.name}" if alias.name else "" 2277 columns = f" AS {columns}" if columns else "" 2278 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2279 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2280 2281 alias = self.sql(expression, "alias") 2282 alias = f" AS {alias}" if alias else "" 2283 return f"{self.lateral_op(expression)} {this}{alias}"
2285 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2286 this = self.sql(expression, "this") 2287 2288 args = [ 2289 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2290 for e in (expression.args.get(k) for k in ("offset", "expression")) 2291 if e 2292 ] 2293 2294 args_sql = ", ".join(self.sql(e) for e in args) 2295 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2296 expressions = self.expressions(expression, flat=True) 2297 limit_options = self.sql(expression, "limit_options") 2298 expressions = f" BY {expressions}" if expressions else "" 2299 2300 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2302 def offset_sql(self, expression: exp.Offset) -> str: 2303 this = self.sql(expression, "this") 2304 value = expression.expression 2305 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2306 expressions = self.expressions(expression, flat=True) 2307 expressions = f" BY {expressions}" if expressions else "" 2308 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2310 def setitem_sql(self, expression: exp.SetItem) -> str: 2311 kind = self.sql(expression, "kind") 2312 kind = f"{kind} " if kind else "" 2313 this = self.sql(expression, "this") 2314 expressions = self.expressions(expression) 2315 collate = self.sql(expression, "collate") 2316 collate = f" COLLATE {collate}" if collate else "" 2317 global_ = "GLOBAL " if expression.args.get("global") else "" 2318 return f"{global_}{kind}{this}{expressions}{collate}"
2328 def lock_sql(self, expression: exp.Lock) -> str: 2329 if not self.LOCKING_READS_SUPPORTED: 2330 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2331 return "" 2332 2333 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2334 expressions = self.expressions(expression, flat=True) 2335 expressions = f" OF {expressions}" if expressions else "" 2336 wait = expression.args.get("wait") 2337 2338 if wait is not None: 2339 if isinstance(wait, exp.Literal): 2340 wait = f" WAIT {self.sql(wait)}" 2341 else: 2342 wait = " NOWAIT" if wait else " SKIP LOCKED" 2343 2344 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str(self, text: str, escape_backslash: bool = True) -> str:
2352 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2353 if self.dialect.ESCAPED_SEQUENCES: 2354 to_escaped = self.dialect.ESCAPED_SEQUENCES 2355 text = "".join( 2356 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2357 ) 2358 2359 return self._replace_line_breaks(text).replace( 2360 self.dialect.QUOTE_END, self._escaped_quote_end 2361 )
2363 def loaddata_sql(self, expression: exp.LoadData) -> str: 2364 local = " LOCAL" if expression.args.get("local") else "" 2365 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2366 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2367 this = f" INTO TABLE {self.sql(expression, 'this')}" 2368 partition = self.sql(expression, "partition") 2369 partition = f" {partition}" if partition else "" 2370 input_format = self.sql(expression, "input_format") 2371 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2372 serde = self.sql(expression, "serde") 2373 serde = f" SERDE {serde}" if serde else "" 2374 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2382 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2383 this = self.sql(expression, "this") 2384 this = f"{this} " if this else this 2385 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2386 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore
2388 def withfill_sql(self, expression: exp.WithFill) -> str: 2389 from_sql = self.sql(expression, "from") 2390 from_sql = f" FROM {from_sql}" if from_sql else "" 2391 to_sql = self.sql(expression, "to") 2392 to_sql = f" TO {to_sql}" if to_sql else "" 2393 step_sql = self.sql(expression, "step") 2394 step_sql = f" STEP {step_sql}" if step_sql else "" 2395 interpolated_values = [ 2396 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2397 if isinstance(e, exp.Alias) 2398 else self.sql(e, "this") 2399 for e in expression.args.get("interpolate") or [] 2400 ] 2401 interpolate = ( 2402 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2403 ) 2404 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2415 def ordered_sql(self, expression: exp.Ordered) -> str: 2416 desc = expression.args.get("desc") 2417 asc = not desc 2418 2419 nulls_first = expression.args.get("nulls_first") 2420 nulls_last = not nulls_first 2421 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2422 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2423 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2424 2425 this = self.sql(expression, "this") 2426 2427 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2428 nulls_sort_change = "" 2429 if nulls_first and ( 2430 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2431 ): 2432 nulls_sort_change = " NULLS FIRST" 2433 elif ( 2434 nulls_last 2435 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2436 and not nulls_are_last 2437 ): 2438 nulls_sort_change = " NULLS LAST" 2439 2440 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2441 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2442 window = expression.find_ancestor(exp.Window, exp.Select) 2443 if isinstance(window, exp.Window) and window.args.get("spec"): 2444 self.unsupported( 2445 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2446 ) 2447 nulls_sort_change = "" 2448 elif self.NULL_ORDERING_SUPPORTED is False and ( 2449 (asc and nulls_sort_change == " NULLS LAST") 2450 or (desc and nulls_sort_change == " NULLS FIRST") 2451 ): 2452 # BigQuery does not allow these ordering/nulls combinations when used under 2453 # an aggregation func or under a window containing one 2454 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2455 2456 if isinstance(ancestor, exp.Window): 2457 ancestor = ancestor.this 2458 if isinstance(ancestor, exp.AggFunc): 2459 self.unsupported( 2460 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2461 ) 2462 nulls_sort_change = "" 2463 elif self.NULL_ORDERING_SUPPORTED is None: 2464 if expression.this.is_int: 2465 self.unsupported( 2466 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2467 ) 2468 elif not isinstance(expression.this, exp.Rand): 2469 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2470 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2471 nulls_sort_change = "" 2472 2473 with_fill = self.sql(expression, "with_fill") 2474 with_fill = f" {with_fill}" if with_fill else "" 2475 2476 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2486 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2487 partition = self.partition_by_sql(expression) 2488 order = self.sql(expression, "order") 2489 measures = self.expressions(expression, key="measures") 2490 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2491 rows = self.sql(expression, "rows") 2492 rows = self.seg(rows) if rows else "" 2493 after = self.sql(expression, "after") 2494 after = self.seg(after) if after else "" 2495 pattern = self.sql(expression, "pattern") 2496 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2497 definition_sqls = [ 2498 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2499 for definition in expression.args.get("define", []) 2500 ] 2501 definitions = self.expressions(sqls=definition_sqls) 2502 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2503 body = "".join( 2504 ( 2505 partition, 2506 order, 2507 measures, 2508 rows, 2509 after, 2510 pattern, 2511 define, 2512 ) 2513 ) 2514 alias = self.sql(expression, "alias") 2515 alias = f" {alias}" if alias else "" 2516 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2518 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2519 limit = expression.args.get("limit") 2520 2521 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2522 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2523 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2524 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2525 2526 return csv( 2527 *sqls, 2528 *[self.sql(join) for join in expression.args.get("joins") or []], 2529 self.sql(expression, "match"), 2530 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2531 self.sql(expression, "prewhere"), 2532 self.sql(expression, "where"), 2533 self.sql(expression, "connect"), 2534 self.sql(expression, "group"), 2535 self.sql(expression, "having"), 2536 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2537 self.sql(expression, "order"), 2538 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2539 *self.after_limit_modifiers(expression), 2540 self.options_modifier(expression), 2541 sep="", 2542 )
def
offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2551 def offset_limit_modifiers( 2552 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2553 ) -> t.List[str]: 2554 return [ 2555 self.sql(expression, "offset") if fetch else self.sql(limit), 2556 self.sql(limit) if fetch else self.sql(expression, "offset"), 2557 ]
2564 def select_sql(self, expression: exp.Select) -> str: 2565 into = expression.args.get("into") 2566 if not self.SUPPORTS_SELECT_INTO and into: 2567 into.pop() 2568 2569 hint = self.sql(expression, "hint") 2570 distinct = self.sql(expression, "distinct") 2571 distinct = f" {distinct}" if distinct else "" 2572 kind = self.sql(expression, "kind") 2573 2574 limit = expression.args.get("limit") 2575 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2576 top = self.limit_sql(limit, top=True) 2577 limit.pop() 2578 else: 2579 top = "" 2580 2581 expressions = self.expressions(expression) 2582 2583 if kind: 2584 if kind in self.SELECT_KINDS: 2585 kind = f" AS {kind}" 2586 else: 2587 if kind == "STRUCT": 2588 expressions = self.expressions( 2589 sqls=[ 2590 self.sql( 2591 exp.Struct( 2592 expressions=[ 2593 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2594 if isinstance(e, exp.Alias) 2595 else e 2596 for e in expression.expressions 2597 ] 2598 ) 2599 ) 2600 ] 2601 ) 2602 kind = "" 2603 2604 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2605 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2606 2607 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2608 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2609 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2610 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2611 sql = self.query_modifiers( 2612 expression, 2613 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2614 self.sql(expression, "into", comment=False), 2615 self.sql(expression, "from", comment=False), 2616 ) 2617 2618 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2619 if expression.args.get("with"): 2620 sql = self.maybe_comment(sql, expression) 2621 expression.pop_comments() 2622 2623 sql = self.prepend_ctes(expression, sql) 2624 2625 if not self.SUPPORTS_SELECT_INTO and into: 2626 if into.args.get("temporary"): 2627 table_kind = " TEMPORARY" 2628 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2629 table_kind = " UNLOGGED" 2630 else: 2631 table_kind = "" 2632 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2633 2634 return sql
2646 def star_sql(self, expression: exp.Star) -> str: 2647 except_ = self.expressions(expression, key="except", flat=True) 2648 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2649 replace = self.expressions(expression, key="replace", flat=True) 2650 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2651 rename = self.expressions(expression, key="rename", flat=True) 2652 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2653 return f"*{except_}{replace}{rename}"
2669 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2670 alias = self.sql(expression, "alias") 2671 alias = f"{sep}{alias}" if alias else "" 2672 sample = self.sql(expression, "sample") 2673 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2674 alias = f"{sample}{alias}" 2675 2676 # Set to None so it's not generated again by self.query_modifiers() 2677 expression.set("sample", None) 2678 2679 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2680 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2681 return self.prepend_ctes(expression, sql)
2687 def unnest_sql(self, expression: exp.Unnest) -> str: 2688 args = self.expressions(expression, flat=True) 2689 2690 alias = expression.args.get("alias") 2691 offset = expression.args.get("offset") 2692 2693 if self.UNNEST_WITH_ORDINALITY: 2694 if alias and isinstance(offset, exp.Expression): 2695 alias.append("columns", offset) 2696 2697 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2698 columns = alias.columns 2699 alias = self.sql(columns[0]) if columns else "" 2700 else: 2701 alias = self.sql(alias) 2702 2703 alias = f" AS {alias}" if alias else alias 2704 if self.UNNEST_WITH_ORDINALITY: 2705 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2706 else: 2707 if isinstance(offset, exp.Expression): 2708 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2709 elif offset: 2710 suffix = f"{alias} WITH OFFSET" 2711 else: 2712 suffix = alias 2713 2714 return f"UNNEST({args}){suffix}"
2723 def window_sql(self, expression: exp.Window) -> str: 2724 this = self.sql(expression, "this") 2725 partition = self.partition_by_sql(expression) 2726 order = expression.args.get("order") 2727 order = self.order_sql(order, flat=True) if order else "" 2728 spec = self.sql(expression, "spec") 2729 alias = self.sql(expression, "alias") 2730 over = self.sql(expression, "over") or "OVER" 2731 2732 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2733 2734 first = expression.args.get("first") 2735 if first is None: 2736 first = "" 2737 else: 2738 first = "FIRST" if first else "LAST" 2739 2740 if not partition and not order and not spec and alias: 2741 return f"{this} {alias}" 2742 2743 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2744 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2750 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2751 kind = self.sql(expression, "kind") 2752 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2753 end = ( 2754 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2755 or "CURRENT ROW" 2756 ) 2757 return f"{kind} BETWEEN {start} AND {end}"
def
bracket_offset_expressions( self, expression: sqlglot.expressions.Bracket, index_offset: Optional[int] = None) -> List[sqlglot.expressions.Expression]:
2770 def bracket_offset_expressions( 2771 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2772 ) -> t.List[exp.Expression]: 2773 return apply_index_offset( 2774 expression.this, 2775 expression.expressions, 2776 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2777 )
2787 def any_sql(self, expression: exp.Any) -> str: 2788 this = self.sql(expression, "this") 2789 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2790 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2791 this = self.wrap(this) 2792 return f"ANY{this}" 2793 return f"ANY {this}"
2798 def case_sql(self, expression: exp.Case) -> str: 2799 this = self.sql(expression, "this") 2800 statements = [f"CASE {this}" if this else "CASE"] 2801 2802 for e in expression.args["ifs"]: 2803 statements.append(f"WHEN {self.sql(e, 'this')}") 2804 statements.append(f"THEN {self.sql(e, 'true')}") 2805 2806 default = self.sql(expression, "default") 2807 2808 if default: 2809 statements.append(f"ELSE {default}") 2810 2811 statements.append("END") 2812 2813 if self.pretty and self.too_wide(statements): 2814 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2815 2816 return " ".join(statements)
2833 def trim_sql(self, expression: exp.Trim) -> str: 2834 trim_type = self.sql(expression, "position") 2835 2836 if trim_type == "LEADING": 2837 func_name = "LTRIM" 2838 elif trim_type == "TRAILING": 2839 func_name = "RTRIM" 2840 else: 2841 func_name = "TRIM" 2842 2843 return self.func(func_name, expression.this, expression.expression)
def
convert_concat_args( self, expression: sqlglot.expressions.Concat | sqlglot.expressions.ConcatWs) -> List[sqlglot.expressions.Expression]:
2845 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2846 args = expression.expressions 2847 if isinstance(expression, exp.ConcatWs): 2848 args = args[1:] # Skip the delimiter 2849 2850 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2851 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2852 2853 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2854 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2855 2856 return args
2858 def concat_sql(self, expression: exp.Concat) -> str: 2859 expressions = self.convert_concat_args(expression) 2860 2861 # Some dialects don't allow a single-argument CONCAT call 2862 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2863 return self.sql(expressions[0]) 2864 2865 return self.func("CONCAT", *expressions)
2876 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2877 expressions = self.expressions(expression, flat=True) 2878 expressions = f" ({expressions})" if expressions else "" 2879 reference = self.sql(expression, "reference") 2880 reference = f" {reference}" if reference else "" 2881 delete = self.sql(expression, "delete") 2882 delete = f" ON DELETE {delete}" if delete else "" 2883 update = self.sql(expression, "update") 2884 update = f" ON UPDATE {update}" if update else "" 2885 return f"FOREIGN KEY{expressions}{reference}{delete}{update}"
2887 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2888 expressions = self.expressions(expression, flat=True) 2889 options = self.expressions(expression, key="options", flat=True, sep=" ") 2890 options = f" {options}" if options else "" 2891 return f"PRIMARY KEY ({expressions}){options}"
2904 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2905 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2906 2907 if expression.args.get("escape"): 2908 path = self.escape_str(path) 2909 2910 if self.QUOTE_JSON_PATH: 2911 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2912 2913 return path
2915 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2916 if isinstance(expression, exp.JSONPathPart): 2917 transform = self.TRANSFORMS.get(expression.__class__) 2918 if not callable(transform): 2919 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2920 return "" 2921 2922 return transform(self, expression) 2923 2924 if isinstance(expression, int): 2925 return str(expression) 2926 2927 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2928 escaped = expression.replace("'", "\\'") 2929 escaped = f"\\'{expression}\\'" 2930 else: 2931 escaped = expression.replace('"', '\\"') 2932 escaped = f'"{escaped}"' 2933 2934 return escaped
def
jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2939 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2940 null_handling = expression.args.get("null_handling") 2941 null_handling = f" {null_handling}" if null_handling else "" 2942 2943 unique_keys = expression.args.get("unique_keys") 2944 if unique_keys is not None: 2945 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2946 else: 2947 unique_keys = "" 2948 2949 return_type = self.sql(expression, "return_type") 2950 return_type = f" RETURNING {return_type}" if return_type else "" 2951 encoding = self.sql(expression, "encoding") 2952 encoding = f" ENCODING {encoding}" if encoding else "" 2953 2954 return self.func( 2955 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2956 *expression.expressions, 2957 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2958 )
2963 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2964 null_handling = expression.args.get("null_handling") 2965 null_handling = f" {null_handling}" if null_handling else "" 2966 return_type = self.sql(expression, "return_type") 2967 return_type = f" RETURNING {return_type}" if return_type else "" 2968 strict = " STRICT" if expression.args.get("strict") else "" 2969 return self.func( 2970 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2971 )
2973 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2974 this = self.sql(expression, "this") 2975 order = self.sql(expression, "order") 2976 null_handling = expression.args.get("null_handling") 2977 null_handling = f" {null_handling}" if null_handling else "" 2978 return_type = self.sql(expression, "return_type") 2979 return_type = f" RETURNING {return_type}" if return_type else "" 2980 strict = " STRICT" if expression.args.get("strict") else "" 2981 return self.func( 2982 "JSON_ARRAYAGG", 2983 this, 2984 suffix=f"{order}{null_handling}{return_type}{strict})", 2985 )
2987 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2988 path = self.sql(expression, "path") 2989 path = f" PATH {path}" if path else "" 2990 nested_schema = self.sql(expression, "nested_schema") 2991 2992 if nested_schema: 2993 return f"NESTED{path} {nested_schema}" 2994 2995 this = self.sql(expression, "this") 2996 kind = self.sql(expression, "kind") 2997 kind = f" {kind}" if kind else "" 2998 return f"{this}{kind}{path}"
3003 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3004 this = self.sql(expression, "this") 3005 path = self.sql(expression, "path") 3006 path = f", {path}" if path else "" 3007 error_handling = expression.args.get("error_handling") 3008 error_handling = f" {error_handling}" if error_handling else "" 3009 empty_handling = expression.args.get("empty_handling") 3010 empty_handling = f" {empty_handling}" if empty_handling else "" 3011 schema = self.sql(expression, "schema") 3012 return self.func( 3013 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3014 )
3016 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3017 this = self.sql(expression, "this") 3018 kind = self.sql(expression, "kind") 3019 path = self.sql(expression, "path") 3020 path = f" {path}" if path else "" 3021 as_json = " AS JSON" if expression.args.get("as_json") else "" 3022 return f"{this} {kind}{path}{as_json}"
3024 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3025 this = self.sql(expression, "this") 3026 path = self.sql(expression, "path") 3027 path = f", {path}" if path else "" 3028 expressions = self.expressions(expression) 3029 with_ = ( 3030 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3031 if expressions 3032 else "" 3033 ) 3034 return f"OPENJSON({this}{path}){with_}"
3036 def in_sql(self, expression: exp.In) -> str: 3037 query = expression.args.get("query") 3038 unnest = expression.args.get("unnest") 3039 field = expression.args.get("field") 3040 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3041 3042 if query: 3043 in_sql = self.sql(query) 3044 elif unnest: 3045 in_sql = self.in_unnest_op(unnest) 3046 elif field: 3047 in_sql = self.sql(field) 3048 else: 3049 in_sql = f"({self.expressions(expression, flat=True)})" 3050 3051 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3056 def interval_sql(self, expression: exp.Interval) -> str: 3057 unit = self.sql(expression, "unit") 3058 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3059 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3060 unit = f" {unit}" if unit else "" 3061 3062 if self.SINGLE_STRING_INTERVAL: 3063 this = expression.this.name if expression.this else "" 3064 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3065 3066 this = self.sql(expression, "this") 3067 if this: 3068 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3069 this = f" {this}" if unwrapped else f" ({this})" 3070 3071 return f"INTERVAL{this}{unit}"
3076 def reference_sql(self, expression: exp.Reference) -> str: 3077 this = self.sql(expression, "this") 3078 expressions = self.expressions(expression, flat=True) 3079 expressions = f"({expressions})" if expressions else "" 3080 options = self.expressions(expression, key="options", flat=True, sep=" ") 3081 options = f" {options}" if options else "" 3082 return f"REFERENCES {this}{expressions}{options}"
3084 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3085 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3086 parent = expression.parent 3087 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3088 return self.func( 3089 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3090 )
3110 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3111 alias = expression.args["alias"] 3112 3113 identifier_alias = isinstance(alias, exp.Identifier) 3114 literal_alias = isinstance(alias, exp.Literal) 3115 3116 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3117 alias.replace(exp.Literal.string(alias.output_name)) 3118 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3119 alias.replace(exp.to_identifier(alias.output_name)) 3120 3121 return self.alias_sql(expression)
def
and_sql( self, expression: sqlglot.expressions.And, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
def
or_sql( self, expression: sqlglot.expressions.Or, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
def
xor_sql( self, expression: sqlglot.expressions.Xor, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
def
connector_sql( self, expression: sqlglot.expressions.Connector, op: str, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3159 def connector_sql( 3160 self, 3161 expression: exp.Connector, 3162 op: str, 3163 stack: t.Optional[t.List[str | exp.Expression]] = None, 3164 ) -> str: 3165 if stack is not None: 3166 if expression.expressions: 3167 stack.append(self.expressions(expression, sep=f" {op} ")) 3168 else: 3169 stack.append(expression.right) 3170 if expression.comments and self.comments: 3171 for comment in expression.comments: 3172 if comment: 3173 op += f" /*{self.pad_comment(comment)}*/" 3174 stack.extend((op, expression.left)) 3175 return op 3176 3177 stack = [expression] 3178 sqls: t.List[str] = [] 3179 ops = set() 3180 3181 while stack: 3182 node = stack.pop() 3183 if isinstance(node, exp.Connector): 3184 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3185 else: 3186 sql = self.sql(node) 3187 if sqls and sqls[-1] in ops: 3188 sqls[-1] += f" {sql}" 3189 else: 3190 sqls.append(sql) 3191 3192 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3193 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3213 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3214 format_sql = self.sql(expression, "format") 3215 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3216 to_sql = self.sql(expression, "to") 3217 to_sql = f" {to_sql}" if to_sql else "" 3218 action = self.sql(expression, "action") 3219 action = f" {action}" if action else "" 3220 default = self.sql(expression, "default") 3221 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3222 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3236 def comment_sql(self, expression: exp.Comment) -> str: 3237 this = self.sql(expression, "this") 3238 kind = expression.args["kind"] 3239 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3240 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3241 expression_sql = self.sql(expression, "expression") 3242 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3244 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3245 this = self.sql(expression, "this") 3246 delete = " DELETE" if expression.args.get("delete") else "" 3247 recompress = self.sql(expression, "recompress") 3248 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3249 to_disk = self.sql(expression, "to_disk") 3250 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3251 to_volume = self.sql(expression, "to_volume") 3252 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3253 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3255 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3256 where = self.sql(expression, "where") 3257 group = self.sql(expression, "group") 3258 aggregates = self.expressions(expression, key="aggregates") 3259 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3260 3261 if not (where or group or aggregates) and len(expression.expressions) == 1: 3262 return f"TTL {self.expressions(expression, flat=True)}" 3263 3264 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3281 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3282 this = self.sql(expression, "this") 3283 3284 dtype = self.sql(expression, "dtype") 3285 if dtype: 3286 collate = self.sql(expression, "collate") 3287 collate = f" COLLATE {collate}" if collate else "" 3288 using = self.sql(expression, "using") 3289 using = f" USING {using}" if using else "" 3290 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3291 3292 default = self.sql(expression, "default") 3293 if default: 3294 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3295 3296 comment = self.sql(expression, "comment") 3297 if comment: 3298 return f"ALTER COLUMN {this} COMMENT {comment}" 3299 3300 visible = expression.args.get("visible") 3301 if visible: 3302 return f"ALTER COLUMN {this} SET {visible}" 3303 3304 allow_null = expression.args.get("allow_null") 3305 drop = expression.args.get("drop") 3306 3307 if not drop and not allow_null: 3308 self.unsupported("Unsupported ALTER COLUMN syntax") 3309 3310 if allow_null is not None: 3311 keyword = "DROP" if drop else "SET" 3312 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3313 3314 return f"ALTER COLUMN {this} DROP DEFAULT"
3330 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3331 compound = " COMPOUND" if expression.args.get("compound") else "" 3332 this = self.sql(expression, "this") 3333 expressions = self.expressions(expression, flat=True) 3334 expressions = f"({expressions})" if expressions else "" 3335 return f"ALTER{compound} SORTKEY {this or expressions}"
3337 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3338 if not self.RENAME_TABLE_WITH_DB: 3339 # Remove db from tables 3340 expression = expression.transform( 3341 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3342 ).assert_is(exp.AlterRename) 3343 this = self.sql(expression, "this") 3344 return f"RENAME TO {this}"
3356 def alter_sql(self, expression: exp.Alter) -> str: 3357 actions = expression.args["actions"] 3358 3359 if isinstance(actions[0], exp.ColumnDef): 3360 actions = self.add_column_sql(expression) 3361 elif isinstance(actions[0], exp.Schema): 3362 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3363 elif isinstance(actions[0], exp.Delete): 3364 actions = self.expressions(expression, key="actions", flat=True) 3365 elif isinstance(actions[0], exp.Query): 3366 actions = "AS " + self.expressions(expression, key="actions") 3367 else: 3368 actions = self.expressions(expression, key="actions", flat=True) 3369 3370 exists = " IF EXISTS" if expression.args.get("exists") else "" 3371 on_cluster = self.sql(expression, "cluster") 3372 on_cluster = f" {on_cluster}" if on_cluster else "" 3373 only = " ONLY" if expression.args.get("only") else "" 3374 options = self.expressions(expression, key="options") 3375 options = f", {options}" if options else "" 3376 kind = self.sql(expression, "kind") 3377 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3378 3379 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3381 def add_column_sql(self, expression: exp.Alter) -> str: 3382 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3383 return self.expressions( 3384 expression, 3385 key="actions", 3386 prefix="ADD COLUMN ", 3387 skip_first=True, 3388 ) 3389 return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3399 def distinct_sql(self, expression: exp.Distinct) -> str: 3400 this = self.expressions(expression, flat=True) 3401 3402 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3403 case = exp.case() 3404 for arg in expression.expressions: 3405 case = case.when(arg.is_(exp.null()), exp.null()) 3406 this = self.sql(case.else_(f"({this})")) 3407 3408 this = f" {this}" if this else "" 3409 3410 on = self.sql(expression, "on") 3411 on = f" ON {on}" if on else "" 3412 return f"DISTINCT{this}{on}"
3441 def div_sql(self, expression: exp.Div) -> str: 3442 l, r = expression.left, expression.right 3443 3444 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3445 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3446 3447 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3448 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3449 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3450 3451 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3452 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3453 return self.sql( 3454 exp.cast( 3455 l / r, 3456 to=exp.DataType.Type.BIGINT, 3457 ) 3458 ) 3459 3460 return self.binary(expression, "/")
3556 def log_sql(self, expression: exp.Log) -> str: 3557 this = expression.this 3558 expr = expression.expression 3559 3560 if self.dialect.LOG_BASE_FIRST is False: 3561 this, expr = expr, this 3562 elif self.dialect.LOG_BASE_FIRST is None and expr: 3563 if this.name in ("2", "10"): 3564 return self.func(f"LOG{this.name}", expr) 3565 3566 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3567 3568 return self.func("LOG", this, expr)
3577 def binary(self, expression: exp.Binary, op: str) -> str: 3578 sqls: t.List[str] = [] 3579 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3580 binary_type = type(expression) 3581 3582 while stack: 3583 node = stack.pop() 3584 3585 if type(node) is binary_type: 3586 op_func = node.args.get("operator") 3587 if op_func: 3588 op = f"OPERATOR({self.sql(op_func)})" 3589 3590 stack.append(node.right) 3591 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3592 stack.append(node.left) 3593 else: 3594 sqls.append(self.sql(node)) 3595 3596 return "".join(sqls)
3605 def function_fallback_sql(self, expression: exp.Func) -> str: 3606 args = [] 3607 3608 for key in expression.arg_types: 3609 arg_value = expression.args.get(key) 3610 3611 if isinstance(arg_value, list): 3612 for value in arg_value: 3613 args.append(value) 3614 elif arg_value is not None: 3615 args.append(arg_value) 3616 3617 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3618 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3619 else: 3620 name = expression.sql_name() 3621 3622 return self.func(name, *args)
def
func( self, name: str, *args: Union[str, sqlglot.expressions.Expression, NoneType], prefix: str = '(', suffix: str = ')', normalize: bool = True) -> str:
3624 def func( 3625 self, 3626 name: str, 3627 *args: t.Optional[exp.Expression | str], 3628 prefix: str = "(", 3629 suffix: str = ")", 3630 normalize: bool = True, 3631 ) -> str: 3632 name = self.normalize_func(name) if normalize else name 3633 return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def
format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3635 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3636 arg_sqls = tuple( 3637 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3638 ) 3639 if self.pretty and self.too_wide(arg_sqls): 3640 return self.indent( 3641 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3642 ) 3643 return sep.join(arg_sqls)
def
format_time( self, expression: sqlglot.expressions.Expression, inverse_time_mapping: Optional[Dict[str, str]] = None, inverse_time_trie: Optional[Dict] = None) -> Optional[str]:
3648 def format_time( 3649 self, 3650 expression: exp.Expression, 3651 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3652 inverse_time_trie: t.Optional[t.Dict] = None, 3653 ) -> t.Optional[str]: 3654 return format_time( 3655 self.sql(expression, "format"), 3656 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3657 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3658 )
def
expressions( self, expression: Optional[sqlglot.expressions.Expression] = None, key: Optional[str] = None, sqls: Optional[Collection[Union[str, sqlglot.expressions.Expression]]] = None, flat: bool = False, indent: bool = True, skip_first: bool = False, skip_last: bool = False, sep: str = ', ', prefix: str = '', dynamic: bool = False, new_line: bool = False) -> str:
3660 def expressions( 3661 self, 3662 expression: t.Optional[exp.Expression] = None, 3663 key: t.Optional[str] = None, 3664 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3665 flat: bool = False, 3666 indent: bool = True, 3667 skip_first: bool = False, 3668 skip_last: bool = False, 3669 sep: str = ", ", 3670 prefix: str = "", 3671 dynamic: bool = False, 3672 new_line: bool = False, 3673 ) -> str: 3674 expressions = expression.args.get(key or "expressions") if expression else sqls 3675 3676 if not expressions: 3677 return "" 3678 3679 if flat: 3680 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3681 3682 num_sqls = len(expressions) 3683 result_sqls = [] 3684 3685 for i, e in enumerate(expressions): 3686 sql = self.sql(e, comment=False) 3687 if not sql: 3688 continue 3689 3690 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3691 3692 if self.pretty: 3693 if self.leading_comma: 3694 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3695 else: 3696 result_sqls.append( 3697 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3698 ) 3699 else: 3700 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3701 3702 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3703 if new_line: 3704 result_sqls.insert(0, "") 3705 result_sqls.append("") 3706 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3707 else: 3708 result_sql = "".join(result_sqls) 3709 3710 return ( 3711 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3712 if indent 3713 else result_sql 3714 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3716 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3717 flat = flat or isinstance(expression.parent, exp.Properties) 3718 expressions_sql = self.expressions(expression, flat=flat) 3719 if flat: 3720 return f"{op} {expressions_sql}" 3721 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3723 def naked_property(self, expression: exp.Property) -> str: 3724 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3725 if not property_name: 3726 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3727 return f"{property_name} {self.sql(expression, 'this')}"
3735 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3736 this = self.sql(expression, "this") 3737 expressions = self.no_identify(self.expressions, expression) 3738 expressions = ( 3739 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3740 ) 3741 return f"{this}{expressions}" if expressions.strip() != "" else this
3751 def when_sql(self, expression: exp.When) -> str: 3752 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3753 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3754 condition = self.sql(expression, "condition") 3755 condition = f" AND {condition}" if condition else "" 3756 3757 then_expression = expression.args.get("then") 3758 if isinstance(then_expression, exp.Insert): 3759 this = self.sql(then_expression, "this") 3760 this = f"INSERT {this}" if this else "INSERT" 3761 then = self.sql(then_expression, "expression") 3762 then = f"{this} VALUES {then}" if then else this 3763 elif isinstance(then_expression, exp.Update): 3764 if isinstance(then_expression.args.get("expressions"), exp.Star): 3765 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3766 else: 3767 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3768 else: 3769 then = self.sql(then_expression) 3770 return f"WHEN {matched}{source}{condition} THEN {then}"
3775 def merge_sql(self, expression: exp.Merge) -> str: 3776 table = expression.this 3777 table_alias = "" 3778 3779 hints = table.args.get("hints") 3780 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3781 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3782 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3783 3784 this = self.sql(table) 3785 using = f"USING {self.sql(expression, 'using')}" 3786 on = f"ON {self.sql(expression, 'on')}" 3787 whens = self.sql(expression, "whens") 3788 3789 returning = self.sql(expression, "returning") 3790 if returning: 3791 whens = f"{whens}{returning}" 3792 3793 sep = self.sep() 3794 3795 return self.prepend_ctes( 3796 expression, 3797 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3798 )
3804 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3805 if not self.SUPPORTS_TO_NUMBER: 3806 self.unsupported("Unsupported TO_NUMBER function") 3807 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3808 3809 fmt = expression.args.get("format") 3810 if not fmt: 3811 self.unsupported("Conversion format is required for TO_NUMBER") 3812 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3813 3814 return self.func("TO_NUMBER", expression.this, fmt)
3816 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3817 this = self.sql(expression, "this") 3818 kind = self.sql(expression, "kind") 3819 settings_sql = self.expressions(expression, key="settings", sep=" ") 3820 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3821 return f"{this}({kind}{args})"
3840 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3841 expressions = self.expressions(expression, flat=True) 3842 expressions = f" {self.wrap(expressions)}" if expressions else "" 3843 buckets = self.sql(expression, "buckets") 3844 kind = self.sql(expression, "kind") 3845 buckets = f" BUCKETS {buckets}" if buckets else "" 3846 order = self.sql(expression, "order") 3847 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3852 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3853 expressions = self.expressions(expression, key="expressions", flat=True) 3854 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3855 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3856 buckets = self.sql(expression, "buckets") 3857 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3859 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3860 this = self.sql(expression, "this") 3861 having = self.sql(expression, "having") 3862 3863 if having: 3864 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3865 3866 return self.func("ANY_VALUE", this)
3868 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3869 transform = self.func("TRANSFORM", *expression.expressions) 3870 row_format_before = self.sql(expression, "row_format_before") 3871 row_format_before = f" {row_format_before}" if row_format_before else "" 3872 record_writer = self.sql(expression, "record_writer") 3873 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3874 using = f" USING {self.sql(expression, 'command_script')}" 3875 schema = self.sql(expression, "schema") 3876 schema = f" AS {schema}" if schema else "" 3877 row_format_after = self.sql(expression, "row_format_after") 3878 row_format_after = f" {row_format_after}" if row_format_after else "" 3879 record_reader = self.sql(expression, "record_reader") 3880 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3881 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3883 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3884 key_block_size = self.sql(expression, "key_block_size") 3885 if key_block_size: 3886 return f"KEY_BLOCK_SIZE = {key_block_size}" 3887 3888 using = self.sql(expression, "using") 3889 if using: 3890 return f"USING {using}" 3891 3892 parser = self.sql(expression, "parser") 3893 if parser: 3894 return f"WITH PARSER {parser}" 3895 3896 comment = self.sql(expression, "comment") 3897 if comment: 3898 return f"COMMENT {comment}" 3899 3900 visible = expression.args.get("visible") 3901 if visible is not None: 3902 return "VISIBLE" if visible else "INVISIBLE" 3903 3904 engine_attr = self.sql(expression, "engine_attr") 3905 if engine_attr: 3906 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3907 3908 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3909 if secondary_engine_attr: 3910 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3911 3912 self.unsupported("Unsupported index constraint option.") 3913 return ""
3919 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3920 kind = self.sql(expression, "kind") 3921 kind = f"{kind} INDEX" if kind else "INDEX" 3922 this = self.sql(expression, "this") 3923 this = f" {this}" if this else "" 3924 index_type = self.sql(expression, "index_type") 3925 index_type = f" USING {index_type}" if index_type else "" 3926 expressions = self.expressions(expression, flat=True) 3927 expressions = f" ({expressions})" if expressions else "" 3928 options = self.expressions(expression, key="options", sep=" ") 3929 options = f" {options}" if options else "" 3930 return f"{kind}{this}{index_type}{expressions}{options}"
3932 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3933 if self.NVL2_SUPPORTED: 3934 return self.function_fallback_sql(expression) 3935 3936 case = exp.Case().when( 3937 expression.this.is_(exp.null()).not_(copy=False), 3938 expression.args["true"], 3939 copy=False, 3940 ) 3941 else_cond = expression.args.get("false") 3942 if else_cond: 3943 case.else_(else_cond, copy=False) 3944 3945 return self.sql(case)
3947 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3948 this = self.sql(expression, "this") 3949 expr = self.sql(expression, "expression") 3950 iterator = self.sql(expression, "iterator") 3951 condition = self.sql(expression, "condition") 3952 condition = f" IF {condition}" if condition else "" 3953 return f"{this} FOR {expr} IN {iterator}{condition}"
3961 def predict_sql(self, expression: exp.Predict) -> str: 3962 model = self.sql(expression, "this") 3963 model = f"MODEL {model}" 3964 table = self.sql(expression, "expression") 3965 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3966 parameters = self.sql(expression, "params_struct") 3967 return self.func("PREDICT", model, table, parameters or None)
3979 def toarray_sql(self, expression: exp.ToArray) -> str: 3980 arg = expression.this 3981 if not arg.type: 3982 from sqlglot.optimizer.annotate_types import annotate_types 3983 3984 arg = annotate_types(arg) 3985 3986 if arg.is_type(exp.DataType.Type.ARRAY): 3987 return self.sql(arg) 3988 3989 cond_for_null = arg.is_(exp.null()) 3990 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
3992 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3993 this = expression.this 3994 time_format = self.format_time(expression) 3995 3996 if time_format: 3997 return self.sql( 3998 exp.cast( 3999 exp.StrToTime(this=this, format=expression.args["format"]), 4000 exp.DataType.Type.TIME, 4001 ) 4002 ) 4003 4004 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4005 return self.sql(this) 4006 4007 return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4009 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4010 this = expression.this 4011 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4012 return self.sql(this) 4013 4014 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4016 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4017 this = expression.this 4018 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4019 return self.sql(this) 4020 4021 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4023 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4024 this = expression.this 4025 time_format = self.format_time(expression) 4026 4027 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4028 return self.sql( 4029 exp.cast( 4030 exp.StrToTime(this=this, format=expression.args["format"]), 4031 exp.DataType.Type.DATE, 4032 ) 4033 ) 4034 4035 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4036 return self.sql(this) 4037 4038 return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4050 def lastday_sql(self, expression: exp.LastDay) -> str: 4051 if self.LAST_DAY_SUPPORTS_DATE_PART: 4052 return self.function_fallback_sql(expression) 4053 4054 unit = expression.text("unit") 4055 if unit and unit != "MONTH": 4056 self.unsupported("Date parts are not supported in LAST_DAY.") 4057 4058 return self.func("LAST_DAY", expression.this)
4067 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4068 if self.CAN_IMPLEMENT_ARRAY_ANY: 4069 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4070 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4071 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4072 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4073 4074 from sqlglot.dialects import Dialect 4075 4076 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4077 if self.dialect.__class__ != Dialect: 4078 self.unsupported("ARRAY_ANY is unsupported") 4079 4080 return self.function_fallback_sql(expression)
4082 def struct_sql(self, expression: exp.Struct) -> str: 4083 expression.set( 4084 "expressions", 4085 [ 4086 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4087 if isinstance(e, exp.PropertyEQ) 4088 else e 4089 for e in expression.expressions 4090 ], 4091 ) 4092 4093 return self.function_fallback_sql(expression)
4101 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4102 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4103 tables = f" {self.expressions(expression)}" 4104 4105 exists = " IF EXISTS" if expression.args.get("exists") else "" 4106 4107 on_cluster = self.sql(expression, "cluster") 4108 on_cluster = f" {on_cluster}" if on_cluster else "" 4109 4110 identity = self.sql(expression, "identity") 4111 identity = f" {identity} IDENTITY" if identity else "" 4112 4113 option = self.sql(expression, "option") 4114 option = f" {option}" if option else "" 4115 4116 partition = self.sql(expression, "partition") 4117 partition = f" {partition}" if partition else "" 4118 4119 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4123 def convert_sql(self, expression: exp.Convert) -> str: 4124 to = expression.this 4125 value = expression.expression 4126 style = expression.args.get("style") 4127 safe = expression.args.get("safe") 4128 strict = expression.args.get("strict") 4129 4130 if not to or not value: 4131 return "" 4132 4133 # Retrieve length of datatype and override to default if not specified 4134 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4135 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4136 4137 transformed: t.Optional[exp.Expression] = None 4138 cast = exp.Cast if strict else exp.TryCast 4139 4140 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4141 if isinstance(style, exp.Literal) and style.is_int: 4142 from sqlglot.dialects.tsql import TSQL 4143 4144 style_value = style.name 4145 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4146 if not converted_style: 4147 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4148 4149 fmt = exp.Literal.string(converted_style) 4150 4151 if to.this == exp.DataType.Type.DATE: 4152 transformed = exp.StrToDate(this=value, format=fmt) 4153 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4154 transformed = exp.StrToTime(this=value, format=fmt) 4155 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4156 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4157 elif to.this == exp.DataType.Type.TEXT: 4158 transformed = exp.TimeToStr(this=value, format=fmt) 4159 4160 if not transformed: 4161 transformed = cast(this=value, to=to, safe=safe) 4162 4163 return self.sql(transformed)
4223 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4224 option = self.sql(expression, "this") 4225 4226 if expression.expressions: 4227 upper = option.upper() 4228 4229 # Snowflake FILE_FORMAT options are separated by whitespace 4230 sep = " " if upper == "FILE_FORMAT" else ", " 4231 4232 # Databricks copy/format options do not set their list of values with EQ 4233 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4234 values = self.expressions(expression, flat=True, sep=sep) 4235 return f"{option}{op}({values})" 4236 4237 value = self.sql(expression, "expression") 4238 4239 if not value: 4240 return option 4241 4242 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4243 4244 return f"{option}{op}{value}"
4246 def credentials_sql(self, expression: exp.Credentials) -> str: 4247 cred_expr = expression.args.get("credentials") 4248 if isinstance(cred_expr, exp.Literal): 4249 # Redshift case: CREDENTIALS <string> 4250 credentials = self.sql(expression, "credentials") 4251 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4252 else: 4253 # Snowflake case: CREDENTIALS = (...) 4254 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4255 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4256 4257 storage = self.sql(expression, "storage") 4258 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4259 4260 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4261 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4262 4263 iam_role = self.sql(expression, "iam_role") 4264 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4265 4266 region = self.sql(expression, "region") 4267 region = f" REGION {region}" if region else "" 4268 4269 return f"{credentials}{storage}{encryption}{iam_role}{region}"
4271 def copy_sql(self, expression: exp.Copy) -> str: 4272 this = self.sql(expression, "this") 4273 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4274 4275 credentials = self.sql(expression, "credentials") 4276 credentials = self.seg(credentials) if credentials else "" 4277 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4278 files = self.expressions(expression, key="files", flat=True) 4279 4280 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4281 params = self.expressions( 4282 expression, 4283 key="params", 4284 sep=sep, 4285 new_line=True, 4286 skip_last=True, 4287 skip_first=True, 4288 indent=self.COPY_PARAMS_ARE_WRAPPED, 4289 ) 4290 4291 if params: 4292 if self.COPY_PARAMS_ARE_WRAPPED: 4293 params = f" WITH ({params})" 4294 elif not self.pretty: 4295 params = f" {params}" 4296 4297 return f"COPY{this}{kind} {files}{credentials}{params}"
4302 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4303 on_sql = "ON" if expression.args.get("on") else "OFF" 4304 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4305 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4306 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4307 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4308 4309 if filter_col or retention_period: 4310 on_sql = self.func("ON", filter_col, retention_period) 4311 4312 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4314 def maskingpolicycolumnconstraint_sql( 4315 self, expression: exp.MaskingPolicyColumnConstraint 4316 ) -> str: 4317 this = self.sql(expression, "this") 4318 expressions = self.expressions(expression, flat=True) 4319 expressions = f" USING ({expressions})" if expressions else "" 4320 return f"MASKING POLICY {this}{expressions}"
4330 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4331 this = self.sql(expression, "this") 4332 expr = expression.expression 4333 4334 if isinstance(expr, exp.Func): 4335 # T-SQL's CLR functions are case sensitive 4336 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4337 else: 4338 expr = self.sql(expression, "expression") 4339 4340 return self.scope_resolution(expr, this)
4348 def rand_sql(self, expression: exp.Rand) -> str: 4349 lower = self.sql(expression, "lower") 4350 upper = self.sql(expression, "upper") 4351 4352 if lower and upper: 4353 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4354 return self.func("RAND", expression.this)
4356 def changes_sql(self, expression: exp.Changes) -> str: 4357 information = self.sql(expression, "information") 4358 information = f"INFORMATION => {information}" 4359 at_before = self.sql(expression, "at_before") 4360 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4361 end = self.sql(expression, "end") 4362 end = f"{self.seg('')}{end}" if end else "" 4363 4364 return f"CHANGES ({information}){at_before}{end}"
4366 def pad_sql(self, expression: exp.Pad) -> str: 4367 prefix = "L" if expression.args.get("is_left") else "R" 4368 4369 fill_pattern = self.sql(expression, "fill_pattern") or None 4370 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4371 fill_pattern = "' '" 4372 4373 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4379 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4380 generate_series = exp.GenerateSeries(**expression.args) 4381 4382 parent = expression.parent 4383 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4384 parent = parent.parent 4385 4386 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4387 return self.sql(exp.Unnest(expressions=[generate_series])) 4388 4389 if isinstance(parent, exp.Select): 4390 self.unsupported("GenerateSeries projection unnesting is not supported.") 4391 4392 return self.sql(generate_series)
def
arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4394 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4395 exprs = expression.expressions 4396 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4397 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4398 else: 4399 rhs = self.expressions(expression) 4400 4401 return self.func(name, expression.this, rhs or None)
4403 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4404 if self.SUPPORTS_CONVERT_TIMEZONE: 4405 return self.function_fallback_sql(expression) 4406 4407 source_tz = expression.args.get("source_tz") 4408 target_tz = expression.args.get("target_tz") 4409 timestamp = expression.args.get("timestamp") 4410 4411 if source_tz and timestamp: 4412 timestamp = exp.AtTimeZone( 4413 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4414 ) 4415 4416 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4417 4418 return self.sql(expr)
4420 def json_sql(self, expression: exp.JSON) -> str: 4421 this = self.sql(expression, "this") 4422 this = f" {this}" if this else "" 4423 4424 _with = expression.args.get("with") 4425 4426 if _with is None: 4427 with_sql = "" 4428 elif not _with: 4429 with_sql = " WITHOUT" 4430 else: 4431 with_sql = " WITH" 4432 4433 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4434 4435 return f"JSON{this}{with_sql}{unique_sql}"
4437 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4438 def _generate_on_options(arg: t.Any) -> str: 4439 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4440 4441 path = self.sql(expression, "path") 4442 returning = self.sql(expression, "returning") 4443 returning = f" RETURNING {returning}" if returning else "" 4444 4445 on_condition = self.sql(expression, "on_condition") 4446 on_condition = f" {on_condition}" if on_condition else "" 4447 4448 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4450 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4451 else_ = "ELSE " if expression.args.get("else_") else "" 4452 condition = self.sql(expression, "expression") 4453 condition = f"WHEN {condition} THEN " if condition else else_ 4454 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4455 return f"{condition}{insert}"
4463 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4464 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4465 empty = expression.args.get("empty") 4466 empty = ( 4467 f"DEFAULT {empty} ON EMPTY" 4468 if isinstance(empty, exp.Expression) 4469 else self.sql(expression, "empty") 4470 ) 4471 4472 error = expression.args.get("error") 4473 error = ( 4474 f"DEFAULT {error} ON ERROR" 4475 if isinstance(error, exp.Expression) 4476 else self.sql(expression, "error") 4477 ) 4478 4479 if error and empty: 4480 error = ( 4481 f"{empty} {error}" 4482 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4483 else f"{error} {empty}" 4484 ) 4485 empty = "" 4486 4487 null = self.sql(expression, "null") 4488 4489 return f"{empty}{error}{null}"
4495 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4496 this = self.sql(expression, "this") 4497 path = self.sql(expression, "path") 4498 4499 passing = self.expressions(expression, "passing") 4500 passing = f" PASSING {passing}" if passing else "" 4501 4502 on_condition = self.sql(expression, "on_condition") 4503 on_condition = f" {on_condition}" if on_condition else "" 4504 4505 path = f"{path}{passing}{on_condition}" 4506 4507 return self.func("JSON_EXISTS", this, path)
4509 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4510 array_agg = self.function_fallback_sql(expression) 4511 4512 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4513 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4514 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4515 parent = expression.parent 4516 if isinstance(parent, exp.Filter): 4517 parent_cond = parent.expression.this 4518 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4519 else: 4520 this = expression.this 4521 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4522 if this.find(exp.Column): 4523 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4524 this_sql = ( 4525 self.expressions(this) 4526 if isinstance(this, exp.Distinct) 4527 else self.sql(expression, "this") 4528 ) 4529 4530 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4531 4532 return array_agg
4540 def grant_sql(self, expression: exp.Grant) -> str: 4541 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4542 4543 kind = self.sql(expression, "kind") 4544 kind = f" {kind}" if kind else "" 4545 4546 securable = self.sql(expression, "securable") 4547 securable = f" {securable}" if securable else "" 4548 4549 principals = self.expressions(expression, key="principals", flat=True) 4550 4551 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4552 4553 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4577 def overlay_sql(self, expression: exp.Overlay): 4578 this = self.sql(expression, "this") 4579 expr = self.sql(expression, "expression") 4580 from_sql = self.sql(expression, "from") 4581 for_sql = self.sql(expression, "for") 4582 for_sql = f" FOR {for_sql}" if for_sql else "" 4583 4584 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4590 def string_sql(self, expression: exp.String) -> str: 4591 this = expression.this 4592 zone = expression.args.get("zone") 4593 4594 if zone: 4595 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4596 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4597 # set for source_tz to transpile the time conversion before the STRING cast 4598 this = exp.ConvertTimezone( 4599 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4600 ) 4601 4602 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def
overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4612 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4613 filler = self.sql(expression, "this") 4614 filler = f" {filler}" if filler else "" 4615 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4616 return f"TRUNCATE{filler} {with_count}"
4618 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4619 if self.SUPPORTS_UNIX_SECONDS: 4620 return self.function_fallback_sql(expression) 4621 4622 start_ts = exp.cast( 4623 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4624 ) 4625 4626 return self.sql( 4627 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4628 )
4630 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4631 dim = expression.expression 4632 4633 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4634 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4635 if not (dim.is_int and dim.name == "1"): 4636 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4637 dim = None 4638 4639 # If dimension is required but not specified, default initialize it 4640 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4641 dim = exp.Literal.number(1) 4642 4643 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4645 def attach_sql(self, expression: exp.Attach) -> str: 4646 this = self.sql(expression, "this") 4647 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4648 expressions = self.expressions(expression) 4649 expressions = f" ({expressions})" if expressions else "" 4650 4651 return f"ATTACH{exists_sql} {this}{expressions}"
4665 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4666 this_sql = self.sql(expression, "this") 4667 if isinstance(expression.this, exp.Table): 4668 this_sql = f"TABLE {this_sql}" 4669 4670 return self.func( 4671 "FEATURES_AT_TIME", 4672 this_sql, 4673 expression.args.get("time"), 4674 expression.args.get("num_rows"), 4675 expression.args.get("ignore_feature_nulls"), 4676 )
def
watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4683 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4684 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4685 encode = f"{encode} {self.sql(expression, 'this')}" 4686 4687 properties = expression.args.get("properties") 4688 if properties: 4689 encode = f"{encode} {self.properties(properties)}" 4690 4691 return encode
4693 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4694 this = self.sql(expression, "this") 4695 include = f"INCLUDE {this}" 4696 4697 column_def = self.sql(expression, "column_def") 4698 if column_def: 4699 include = f"{include} {column_def}" 4700 4701 alias = self.sql(expression, "alias") 4702 if alias: 4703 include = f"{include} AS {alias}" 4704 4705 return include
def
partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4711 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4712 partitions = self.expressions(expression, "partition_expressions") 4713 create = self.expressions(expression, "create_expressions") 4714 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def
partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4716 def partitionbyrangepropertydynamic_sql( 4717 self, expression: exp.PartitionByRangePropertyDynamic 4718 ) -> str: 4719 start = self.sql(expression, "start") 4720 end = self.sql(expression, "end") 4721 4722 every = expression.args["every"] 4723 if isinstance(every, exp.Interval) and every.this.is_string: 4724 every.this.replace(exp.Literal.number(every.name)) 4725 4726 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4739 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4740 kind = self.sql(expression, "kind") 4741 option = self.sql(expression, "option") 4742 option = f" {option}" if option else "" 4743 this = self.sql(expression, "this") 4744 this = f" {this}" if this else "" 4745 columns = self.expressions(expression) 4746 columns = f" {columns}" if columns else "" 4747 return f"{kind}{option} STATISTICS{this}{columns}"
4749 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4750 this = self.sql(expression, "this") 4751 columns = self.expressions(expression) 4752 inner_expression = self.sql(expression, "expression") 4753 inner_expression = f" {inner_expression}" if inner_expression else "" 4754 update_options = self.sql(expression, "update_options") 4755 update_options = f" {update_options} UPDATE" if update_options else "" 4756 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def
analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4767 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4768 kind = self.sql(expression, "kind") 4769 this = self.sql(expression, "this") 4770 this = f" {this}" if this else "" 4771 inner_expression = self.sql(expression, "expression") 4772 return f"VALIDATE {kind}{this}{inner_expression}"
4774 def analyze_sql(self, expression: exp.Analyze) -> str: 4775 options = self.expressions(expression, key="options", sep=" ") 4776 options = f" {options}" if options else "" 4777 kind = self.sql(expression, "kind") 4778 kind = f" {kind}" if kind else "" 4779 this = self.sql(expression, "this") 4780 this = f" {this}" if this else "" 4781 mode = self.sql(expression, "mode") 4782 mode = f" {mode}" if mode else "" 4783 properties = self.sql(expression, "properties") 4784 properties = f" {properties}" if properties else "" 4785 partition = self.sql(expression, "partition") 4786 partition = f" {partition}" if partition else "" 4787 inner_expression = self.sql(expression, "expression") 4788 inner_expression = f" {inner_expression}" if inner_expression else "" 4789 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4791 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4792 this = self.sql(expression, "this") 4793 namespaces = self.expressions(expression, key="namespaces") 4794 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4795 passing = self.expressions(expression, key="passing") 4796 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4797 columns = self.expressions(expression, key="columns") 4798 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4799 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4800 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4806 def export_sql(self, expression: exp.Export) -> str: 4807 this = self.sql(expression, "this") 4808 connection = self.sql(expression, "connection") 4809 connection = f"WITH CONNECTION {connection} " if connection else "" 4810 options = self.sql(expression, "options") 4811 return f"EXPORT DATA {connection}{options} AS {this}"
4816 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4817 variable = self.sql(expression, "this") 4818 default = self.sql(expression, "default") 4819 default = f" = {default}" if default else "" 4820 4821 kind = self.sql(expression, "kind") 4822 if isinstance(expression.args.get("kind"), exp.Schema): 4823 kind = f"TABLE {kind}" 4824 4825 return f"{variable} AS {kind}{default}"
4827 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4828 kind = self.sql(expression, "kind") 4829 this = self.sql(expression, "this") 4830 set = self.sql(expression, "expression") 4831 using = self.sql(expression, "using") 4832 using = f" USING {using}" if using else "" 4833 4834 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4835 4836 return f"{kind_sql} {this} SET {set}{using}"
def
combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str:
4855 def put_sql(self, expression: exp.Put) -> str: 4856 props = expression.args.get("properties") 4857 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4858 this = self.sql(expression, "this") 4859 target = self.sql(expression, "target") 4860 return f"PUT {this} {target}{props_sql}"